2

次のルートを持つレールアプリがあります

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 ==)
4

2 に答える 2

0

これはばかげているように聞こえるかもしれませんが、ルート ファイルの最後に最初の 'root :to => "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 という名前の 2 つの名前付きルートがあることがわかります。ルートは「最初の一致」であるため、テストで間違ったルートを選択している可能性があります。

于 2011-08-23T19:00:52.677 に答える
0

私は問題を解決したと思います。確認コードを

it "should redirect to root" do
  current_url.should == root_url("en")
end

動作します。

私の問題の原因は、webrat が実際にリダイレクトに従っていることが原因であると想定しているため、最初のテストでは、リダイレクト後の 2 番目の応答の応答コードをテストしていました。

于 2011-08-28T09:11:47.077 に答える