Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec - Test that rails view renders a specific partial

I have a rails 3.2.13 app running rspec-rails 2.14.0 and am trying to confirm that a view renders a particular partial in my test. It actually does work, but I need to add this test. Here's what I have so far:

require 'spec_helper'

describe 'users/items/index.html.haml' do
  let(:current_user) { mock_model(User) }

  context 'when there are no items for this user' do
    items = nil

    it 'should render empty inventory partial' do
      response.should render_template(:partial => "_empty_inventory")
    end

  end
end

This runs without error, but does not pass. The failure is:

Failure/Error: response.should render_template(:partial => "_empty_inventory")
   expecting partial <"_empty_inventory"> but action rendered <[]>

Thanks for any ideas.

EDIT

This works for me, but Peter's solution is better...

context 'when there are no items for this user' do

  before do
    view.stub(current_user: current_user)
    items = nil
    render
  end

  it 'should render empty inventory partial' do
    view.should render_template(:partial => "_empty_inventory")
  end

end 

For some reason it was counter-intuitive to me to have to call render on a view, but there you go...

like image 870
panzhuli Avatar asked Nov 04 '13 03:11

panzhuli


1 Answers

So the way one usually tests whether a particular partial is rendered in a view spec is by testing the actual content of the partial. For example, assume that your _empty_inventory parial has the message 'There is no inventory'. Then you might have a spec like:

  it "displays the empty inventory message" do
    render
    rendered.should_not have_content('There is no inventory')
  end

Alternately, you could use a controller spec, in which case you need to call the 'render_views' method when setting up the spec. Then you can do something similar to

it 'should render empty inventory partial' do
  get :index, :user_id => user.id
  response.should render_template(:partial => "_empty_inventory")
end

Assuming you've set up the state for the contoller spec.

like image 146
Peter Goldstein Avatar answered Nov 15 '22 10:11

Peter Goldstein