首页 > 解决方案 > 设计和 RSpec - 用户仅在第一次测试中登录

问题描述

我正在为使用 RSpec 的 RESTFul 控制器编写规范,我需要通过 Devise 登录用户。

以下代码导致用户在第一个it语句中正确登录,但不是第二个。

如果我更改beforeafterfrom :allto :each,这两个语句都会失败,就好像用户没有登录一样。

RSpec.describe SomeController, type: :controller do
  describe '#index' do
    before :all do
      @account = create(:account)
      @user = @account.users.first
      sign_in(@user)
    end

    after :all do
      sign_out(@user)
    end

    it 'should load all objects of a @user' do
      get :index

      body = JSON.parse(response.body)
      expect(body['data'].length).to eq(4)
      expect(response).to have_http_status(:ok)
    end

    it 'should load all objects of a @user' do
      get :index

      body = JSON.parse(response.body)
      expect(body['data'].length).to eq(4)
      expect(response).to have_http_status(:ok)
    end
  end
end

我发现这个问题的答案很少,一个是在测试 ENV 中使用 Cookie Store(它没有修复它),还有一个带有设计的 RSpec - 只有第一个测试被登录,这也没有帮助我解决这个问题。

RSpec 3.7 Rails 5.2 设计 4.4

帮助将不胜感激!谢谢

标签: ruby-on-railsrspecdevise

解决方案


如果您正在使用 ActAsTenant,请不要忘记将 ActAsTenant.current_tenant = nil, 放在 before(:each) 的开头。这给我带来了与您描述的相同的问题


推荐阅读