【发布时间】: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