RSpec - 测试竞争条件

时间:2017-10-11 13:45:39

标签: ruby-on-rails ruby rspec race-condition

我正在尝试编写RSpec控制器测试,根据this blog post检查竞争条件,但创建的Thread不会“看到”开头创建的User测试。 该博文建议将config.use_transactional_fixtures更改为false,但即使使用此设置,User也不可见。

以下是测试:

it "avoids race conditions" do
  u = create(:user, :without_settings)
  u_2 = create(:user, :without_settings)

  wait_for_it = true

  threads = Array.new(4).map {
    Thread.new do
      true while wait_for_it
      # send the request
      signed_post(
        u,
        api_v1_blockades_path,
        params: {
          blockade: {
            blocked_user_id: u_2.id,
            reason: 11
          }
        }
      )
    end
  }

  wait_for_it = false
  threads.map(&:join)

  expect(u.blockades.count).to eq(1)
end

对于身份验证,我正在使用ApiAuth gem

before_action :api_authenticate

private

def current_user
  @current_user ||= User.find_by(id: ApiAuth.access_id(request))
end

def api_authenticate
  head(:unauthorized) unless current_user && ApiAuth.authentic?(request, current_user.auth_token)
end

0 个答案:

没有答案