Trouble on testing a JavaScript redirection

可紊 提交于 2019-12-13 02:00:35

问题


I am using Ruby on Rails 3.1.0 and the rspec-rails 2 gem. I would like to test a JavaScript redirection but I am some trouble on doing that.

In my controller file I have:

respond_to do |format|
  format.js { render :js => "window.location.replace('#{users_url}');" }
end

In my spec file I have:

it "should redirect" do
  xhr :post, :create
  response.should redirect_to(users_url)
end

If I run the spec I get the following:

 Failure/Error: response.should redirect_to(users_url)
   Expected response to be a <:redirect>, but was <200>

How can I implement the spec code so to correctly test the JavaScript redirection?


ATTEMPTS AT SOLUTION

If I use

response.should render_template("window.location.replace('#{users_url}');")

I get

 Failure/Error: response.should render_template("window.location.replace('#{users_url}');")
   expecting <"window.location.replace('http://<my_application_url>/users');"> but rendering with <"">

If I use

response.should render_template(:js => "window.location.replace('#{users_url}');")

the spec successfully passes, but too much! That is, I can state also the following and the spec will (unexpectedly) pass:

response.should render_template(:js => "every_thing")

I have also seen this question\answer and the proposed solution works, but I think that is the best solution to accomplish what I aim.


回答1:


RSpec controller specs use the rack_test driver, which does not execute Javascript. To test pages that use Javascript for redirection, you should really look at another driver.

Capybara with selenium-webdriver does this nicely. RSpec request specs replace your controller specs for those tests that rely on Javascript.



来源:https://stackoverflow.com/questions/7581502/trouble-on-testing-a-javascript-redirection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!