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?
CodePudding user response:
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