我有一个带有以下路线的 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 ==)