次のルートを持つレールアプリがあります
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 ==)