0

M. Hartl Rails チュートリアルを使用してアプリを作成しました。だから私はUserモデルとすべてcurrent_usersigned_in_userメソッドを持っています。

次のテストをパスさせたい:

describe "submitting a PATCH request to the Users#update action" do
  before do
    be_signed_in_as FactoryGirl.create(:user)
    patch user_path(FactoryGirl.create(:user))
  end
  specify { expect(response).to redirect_to(root_path) }
end

しかし、テストは失敗します:

 Failure/Error: specify { expect(response).to redirect_to(root_path) }
   Expected response to be a redirect to <http://www.example.com/> but was a redirect to <http://www.example.com/signin>.
   Expected "http://www.example.com/" to be === "http://www.example.com/signin".

これがユーザーコントローラーの一部です

class UsersController < ApplicationController

  before_action :signed_in_user, only: [:index, :edit, :update, :destroy]
  before_action :correct_user,   only: [:edit, :update]
  before_action :admin_user, only: :destroy

      .
      .
      .
      .
  private

    def signed_in_user
      unless !current_user.nil?
        store_url
        redirect_to signin_url, notice: t('sign.in.please')
      end
    end

    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_path) unless current_user?(@user)
    end

    def admin_user
      redirect_to(root_path) unless current_user.admin?
    end
end

行を削除するbefore_create :signed_in_user...と、テストに合格します。しかし、それはなぜですか?spec メソッドは他のbe_signed_in_asすべてのテスト (~ 1k) で機能しているため、その理由はその中にあるに違いありませんspecify { expect(response)

4

2 に答える 2

0

あなたのテストは、user_pathログインしているユーザーとは異なるユーザーに対して行われるため、correct_userフィルターによってルートにリダイレクトされます。ログインしているユーザーを保存し、それを に使用する必要がありますuser_path

于 2013-09-30T14:50:40.070 に答える
0

を呼び出すたびにFactoryGirl.create(:user)、追加のユーザーを作成しています。リストしたコードは、データベースに 2 つの個別のユーザー レコードを作成しています。したがって、このテスト用に 2 人の異なるユーザーを作成するつもりでない限り、おそらくbeforeブロックの前に次のような行が必要です。

let(:user) { FactoryGirl.create(:user) }

次にuser、1 つのユーザー レコードが必要なすべての場所を参照します。

于 2013-09-30T19:06:52.787 に答える