Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec Controller testing with Javascript

Tags:

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

like image 527
hoitomt Avatar asked Sep 26 '12 14:09

hoitomt


1 Answers

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
like image 89
Jim Stewart Avatar answered Sep 30 '22 01:09

Jim Stewart