Rspec测试控制器用户将不会保持登录状态

时间:2019-02-22 21:51:26

标签: ruby-on-rails rspec

我要运行2个测试,我需要登录。

RSpec.describe MealsController, type: :controller do

    before(:all) do 
        Location.create! name: 'test'
        @user = create(:user, :admin)
        @client1 = create(:client, user_id: @user.id)
        @client2 = create(:client)
        login_as @user, scope: :user
    end

    describe "GET index" do 
        it 'expects successfull index load' do
            get :index
            expect(response.status).to eq(200)
        end

        it 'expects order to be' do
            get :index, {:params => { :client_id => @client2.id }}
            expect(session[:orderClient]).to eq(@client2.id)
        end
    end
end

第一个测试成功,但是第二个失败,并显示以下响应:

Failure/Error: redirect_to new_user_session_path, notice: "You must be signed in to access this page."

我不明白为什么get :index在第一个测试中有效,但在第二个测试中无效。我尝试将login_as @user, scope: :user行直接添加到第二个测试中,并且发生相同的错误。

1 个答案:

答案 0 :(得分:0)

before(:all)在describe块的开头仅运行一次。尝试改用before(:each),它将在每个规范(或it)之前运行。

或者,因为它是默认设置,所以只需before do