如何让工厂只为 Rspec 中的所有测试创建一次数据
这是我的代码的一个简化版本:
frozen_string_literal: true
RSpec.describe MyObject do
let!(:my_object) { create(:my_object, name: 'This Name') }
let!(:my_ojbect_2) { create(:my_object_2, obj: my_object) }
describe '#my_data' do
subject { my_object.my_data }
context 'when a' do
...
...
it { is_expected.to eq expected_value }
end
context 'when b' do
...
...
it { is_expected.to eq expected_value }
end
context 'when' do
...
...
it { byebug }
end
end
end
当测试在 byebug 处停止时,我注意到 my_object 在数据库中创建了多次。有没有办法让 my_object 只创建一次?
Here is a little simplified version of my code:
frozen_string_literal: true
RSpec.describe MyObject do
let!(:my_object) { create(:my_object, name: 'This Name') }
let!(:my_ojbect_2) { create(:my_object_2, obj: my_object) }
describe '#my_data' do
subject { my_object.my_data }
context 'when a' do
...
...
it { is_expected.to eq expected_value }
end
context 'when b' do
...
...
it { is_expected.to eq expected_value }
end
context 'when' do
...
...
it { byebug }
end
end
end
When the test stopped at the byebug, I noticed that my_object was created multiple times in the database. Is there a way to have my_object only create one time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果测试对象的多个副本在测试之间持续存在,这会给您的测试带来巨大的问题,并且它们不可靠。
在两次测试之间你必须有一个干净的记录。有很多方法可以做到这一点,但工厂、固定装置、事务固定装置等可能会变得复杂。
我个人几乎总是最终使用数据库清理器。
看看数据库清理器
If multiple copies of test objects are persisting between tests this creates huge problems for your tests, and they cannot be relied on.
You have to have a clean slate between tests. There are a number of ways to do this, but it can get complicated with factories, fixtures, transactional fixtures, etc.
I personally almost always end up using a database cleaner.
Have a look at Database Cleaner