我正在尝试编写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