开发者

Trouble on testing a JavaScript redirection

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 <:red开发者_Python百科irect>, 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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜