20

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

hoitomt
  • 670
  • 1
  • 6
  • 16

2 Answers2

47

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
Jim Stewart
  • 16,964
  • 5
  • 69
  • 89
19

Ok, I figured out what I was doing wrong. I was passing a parameters hash in with my test and the format needs to be included in the same hash. so instead of this:

@params = {:chip_color => 'red'}
...
post :add_chips, @params, :format => 'js'

It needs to look like this

@params = {:chip_color => 'red', :format => 'js'}
...
post :add_chips, @params
hoitomt
  • 670
  • 1
  • 6
  • 16