测试 JavaScript 重定向的问题 [英] Trouble on testing a JavaScript redirection

查看:32
本文介绍了测试 JavaScript 重定向的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Ruby on Rails 3.1.0 和 rspec-rails 2 gem.我想测试 JavaScript 重定向,但我在这样做时遇到了一些麻烦.

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>

如何实现规范代码以正确测试 JavaScript 重定向?

尝试解决方案

如果我使用

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

我明白

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

如果我使用

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 控制器规范使用 rack_test 驱动程序,它不执行 Javascript.要测试使用 Javascript 进行重定向的页面,您确实应该查看其他驱动程序.

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 使用 selenium-webdriver 可以很好地做到这一点.RSpec 请求规范取代了那些依赖 Javascript 的测试的控制器规范.

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

这篇关于测试 JavaScript 重定向的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆