开发者

Rails Functional Test assert_select finds nothing after AJAX post

On Rails 2.3.2 I'开发者_如何转开发m trying to test a view in a functional test

def test_view
 get :form
 xhr :post, :add_to_cart, {:id => 1}
 post :create, {:param => value}
 assert_select 'title', 'Success!'
end

But keep getting a failure:

Expected at least 1 element matching "title", found 0. is not true.

I understand that you cannot use 'assert_select' after a xhr call, but in this case, I'm doing it AFTER a regular post request.

If I drop the xhr request

def test_view
 get :form
 post :create, {:param => value}
 assert_select 'title', 'Success!'
end

Then it works like charm. I could set the cart (which I store in session) manually, but then I would not be really testing the view...

Any ideas?


I think you've already figured it out -- functional tests expect a single controller action, not multiple actions. I'd suggest replacing this with an integration test.


If you make an xhr request then @response.content_type == 'text/javascript' and assert_select won't work with it. To get it to work you have to change the content type to 'text/html', like so:

xhr(:get, something)
@response.content_type = 'text/html'
assert_select 'title', 'Success!'


I had the same problem. As noted above, it comes from ActionController setting the content-type to text-javascript, while assert_select works with text/html. The better way to set it though is not to mingle with @response in the test, but in the controller, like this:

respond_to do |format| 
  format.html {...}
end

This will force content type to text/html.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜