登录用户似乎无法登录

时间:2013-09-30 12:05:50

标签: ruby-on-rails authentication rspec capybara

我使用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...行,则测试通过。 但那是为什么呢? be_signed_in_as规范方法适用于所有其他测试(~1k),因此原因必须在specify { expect(response)内。

2 个答案:

答案 0 :(得分:0)

对于与您登录时不同的用户,您的测试结果为user_path,因此您的correct_user过滤器会将您重定向到根目录。您需要保存您登录的用户,并将其用于user_path

答案 1 :(得分:0)

每次拨打FactoryGirl.create(:user)时,您都会创建一个额外的用户。您列出的代码是在数据库中创建两个单独的用户记录。因此,除非您打算为此测试创建两个不同的用户,否则您应该在before块之前有一行:

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

然后只需在您想要一个用户记录的任何地方引用user

相关问题