Rspec Controller testing with Javascript

hoitomt picture hoitomt · Sep 26, 2012 · Viewed 10.1k times · Source

How do you test a controller in Rspec if the controller only responds with javascript? For example this would be my actual code:

some view.html.erb

link_to 'More Chips', add_chips_path, :remote => true

chips_controller

def add_chips
  Chips.create(:color => :red)
  @chips = Chips.all
end

add_chips.js.erb

$('#chip_count').html('<%=j render("chips/list", :chips => @chips) %>');

Rspec Test

spec/controllers/chips_controller_spec

it "should add chips" do 
  post :add_chips, :format => 'js'
end

When I try to post to this using RSpec I get a Missing Template error because it is sending an HTML request but there isn't an HTML view. I've tried passing in a format but that doesn't seem to work. I know I can put in a "dummy" html view to make it pass but that seems like a hack.

Thanks

Answer

Jim Stewart picture Jim Stewart · Mar 17, 2013

If you're trying to perform an Ajax request from a controller spec, instead of doing post :add_chips and passing the format as a parameter, you should do:

xhr :post, :add_chips, @params

...without format in params. That will do a JavaScript request and respond with the .js template.

Update:

In recent versions of Rails/RSpec, you should instead do:

post :add_chips, params: @params, xhr: true