【问题标题】:Trouble on testing a JavaScript redirection测试 JavaScript 重定向时遇到问题
【发布时间】:2011-09-28 10:03:43
【问题描述】:

我正在使用 Ruby on Rails 3.1.0 和 rspec-rails 2 gem。我想测试一个 JavaScript 重定向,但这样做有点麻烦。

在我的控制器文件中,我有:

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

在我的规范文件中:

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

如果我运行规范,我会得到以下信息:

 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}');")

规范成功通过,但太多了!也就是说,我还可以声明以下内容,并且规范将(出乎意料地)通过:

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

我也见过this question\answer 并且建议的解决方案有效,但我认为这是实现我的目标的最佳解决方案。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 rspec rspec2


    【解决方案1】:

    RSpec 控制器规范使用 rack_test 驱动程序,它不执行 Javascript。要测试使用 Javascript 进行重定向的页面,您应该看看另一个驱动程序。

    Capybara 和 selenium-webdriver 可以很好地做到这一点。 RSpec 请求规范替换了那些依赖 Javascript 的测试的控制器规范。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 2016-12-31
      • 2011-12-16
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      相关资源
      最近更新 更多