evedovelli
evedovelli

Reputation: 2135

Error testing rendering of partial with rspec

I'm writing rspec tests for my controller and trying to test the rendering of a partial, when the action is triggered by an AJAX requisition.

In my controller code, I have:

def new
  ...
  respond_to do |format|
    format.html { render action: "new" }
    format.js   { }
  end
end

I have the files new.html.erb and new.js.erb placed the correct view directory.

And my rspec test is the following:

it "should render the new partial" do
  get :new, :format => 'js'
  response.should render_template(:partial => 'new')
end

When executing this rspec test I get the following error:

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

Can somebody figure why I am getting this error? What am I doing wrong?

Thank you

Upvotes: 0

Views: 2203

Answers (1)

Kingsley Ijomah
Kingsley Ijomah

Reputation: 3403

According to rails guide, the syntax is slightly different:

http://edgeguides.rubyonrails.org/upgrading_ruby_on_rails.html#csrf-protection-from-remote-script-tags

Your test should be something like:

it 'assigns instance of Item to @item and renders new.js.erb' do  
    xhr :get, :new, format: :js
    expect(assigns[:item]).to be_an_instance_of Item
    expect(response).to render_template('new')
end

Your controller would look something like:

class ItemsController < ApplicationController
   def new
     @item = Item.new
   end
 end

Your view will be a .js.erb file

 items/new.js.erb

Upvotes: 4

Related Questions