我有一个带有以下路线的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无法识别为重定向的重定向?
根据评论,我修改了测试以验证状态代码
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 ==)
答案 0 :(得分:0)
我知道这可能听起来很愚蠢,但尝试放置第一个'root:to =&gt;路径文件底部的“pages#home”'。您也可以尝试:
scope "/:locale", :as => "localized" do
root :to => "pages#home"
...
match "/sign_in" => "sessions#new"
resources :sessions, :only => [:new, :create]
end
root :to => "pages#home"
然后在您的测试中,您将检查重定向到localized_root_path
。
我可能很疯狂,但我认为这可能是与命名路线的名称冲突。如果检查rake routes
,您可能会发现有两条名为root的命名路由。由于路线是“第一次匹配”,您可能只是在测试中选择了错误的路线。
答案 1 :(得分:0)
我想我解决了这个问题。将验证码更改为
it "should redirect to root" do
current_url.should == root_url("en")
end
作品。
我认为我的问题的原因是因为webrat实际上遵循重定向,所以在我的原始测试中,我在重定向之后测试第二个响应的响应代码。