【发布时间】:2011-08-18 21:18:06
【问题描述】:
我有一个带有以下路线的 Rails 应用程序
root :to => "pages#home"
scope "/:locale" do
root :to => "pages#home"
...
match "/sign_in" => "sessions#new"
resources :sessions, :only => [:new, :create]
end
我的 ApplicationController 包含一个 default_url_options(),它会自动设置语言环境选项
我的 SessionsController 包含以下内容
class SessionsController < ApplicationController
def new
end
def create
redirect_to root_path
end
end
所以还没有任何逻辑,只是一个重定向。当我在浏览器中运行应用程序时,转到登录页面,提交表单(发布到 /en/sessions),然后它按预期工作:我被重定向到 /en
但是集成测试无法识别重定向
describe "sign-in" do
before(:each) do
visit "/en/sign_in"
@user = Factory.create(:user)
end
context "with valid attributes" do
before(:each) do
fill_in "email", :with => @user.email
fill_in "password", :with => @user.password
end
it "should redirect to root" do
click_button "Sign in"
response.should be_redirect
response.should redirect_to "/en"
end
end
end
测试失败并显示消息
5) Authentication sign-in with valid attributes should redirect to root
Failure/Error: response.should be_redirect
expected redirect? to return true, got false
因此,即使应用程序正确重定向,RSpec 也不会将响应视为重定向。
如果我只是为了好玩,把create的实现改成
def create
redirect_to new_user_path
end
然后我收到错误消息
6) SessionsController POST 'create' with valid user should redirect to root
Failure/Error: response.should redirect_to root_path
Expected response to be a redirect to <http://test.host/en> but was a redirect to <http://test.host/en/users/new>
这当然是预期的错误消息,因为函数现在重定向到错误的 url。但是为什么 new_user_path 会导致 RSpec 视为重定向的重定向,而 root_path 会导致 RSpec 无法识别为重定向的重定向?
更新
基于cmets,我修改测试验证状态码
it "should redirect to root" do
click_button "Sign in"
response.status.should == 302
response.should be_redirect
response.should redirect_to "/en"
end
导致错误
5) Authentication sign-in with valid attributes should redirect to root
Failure/Error: response.status.should == 302
expected: 302
got: 200 (using ==)
【问题讨论】:
-
可能是 rspec 的错误,您是否尝试检查响应 http 代码?
-
可能与github.com/rspec/rspec-core/pull/410这个问题有关。尝试使用最新版本的 rspec
-
我尝试使用 github 的 RSpec 版本,但没有帮助
标签: ruby-on-rails-3 rspec2 rspec-rails