RSPECのレンダリングテンプレートの地元の人々を検証する方法
-
27-10-2019 - |
質問
コントローラーのテンプレートをレンダリングするために渡された地元の人々をどのように検証するのだろうか
コントローラ:
def lelf_panel
# ...
if some_condition
locals_hash = some_very_long_hash_A
else
locals_hash = some_very_long_hash_B
end
render :partial => "left_panel", :layout => false, :locals => locals_hash
end
現在の仕様:
it 'should render correct template for lelf_panel' do
# ...
get 'left_panel'
response.should render_template('system/_left_panel')
end
このコントローラーのRCOVを完了する必要があるため、両方の「some_condition」の結果をカバーするために仕様を追加/変更する必要があります。そして、「Lelf_Panel」の地元の人々がレンダリングに合格したのを検証したいと思います。まるでrender_templateのみを検証するかのように、両方の結果にレンダリングされた部分ページは同じです。
rspec docsで「render_template」をチェックしますhttp://rubydoc.info/gems/rspec-rails/2.8.1/rspec/rails/matchers/rendertemplate:RENDER_TEMPLATE
メッセージにのみ提供され、2番目のパラメーションが提供されます。
解決
私の知る限り、あなたが説明している方法でテンプレートについて地元の人々を直接調べる方法はありません。
locals_hashを@locals_hashに変更してから、assions(:locals_hash)を介して結果を調べることができます。
または、結果のHTMLでセレクターを使用して、いくつかの指標コンテンツがあることを確認できます。たとえば、locals_hashがページのタイトルに影響する場合、結果のHTMLページタイトルが期待していることを確認します。
他のヒント
を使用する代わりに render_template
Matcherでは、コントローラーオブジェクトで期待を使用できます。
it 'should render correct template for lefl_panel' do
# ...
allow(controller).to receive(:render).with no_args
expect(controller).to receive(:render).with({
:partial => 'system/_left_panel',
:layout => false,
:locals => some_very_long_hash_A
})
get 'left_panel'
end
@user2490003のコメントからの提案を含む @ryan -ahearnの答えと同じですが、すべてがより柔軟でRSPEC 3のものになります。
# Safe to set globally, since actions can either render or redirect once or fail anyway
before do
allow(controller).to receive(:render).and_call_original
end
describe "get left panel" do
before do
# other setup
get 'left_panel'
end
it 'should render correct template for lelf_panel' do
# Sadly, render_template is primitive (no hash_including, no block with args, etc.)
expect(subject).to render_template('system/_left_panel')
end
it 'should render with correct local value' do
expect(controller).to have_received(:render) do |options|
expect(options[:locals][:key_from_very_long_hash]).to eq('value_of_key_from_very_long_hash')
end
end
end