I'm using Fabrication-gem gem, with DatabaseCleaner and Mongoid ORM on RSpec tests. Here are my scripts:
spec/support/database_cleaner.rb
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.clean_with(:truncation)
end
end
spec/fabricators/client_fabricators.rb
Fabricator(:client) do
auth_id { (SecureRandom.hex)[0..3] }
base_url { Faker::Internet.url }
end
Finally, spec/requests/clients_spec.rb
before(:all) do
DatabaseCleaner.start
@clients = Fabricate.times(2, :client)
end
after(:all) do # Use after :all so data stays around until the end of the block
DatabaseCleaner.clean
end
it {...}
it {...}
...
Unfortunately, I get as many errors as I have it {...} blocks in my context, all with the same error message from Mongoid:
Failure/Error: @clients = Fabricate.times(2, :client)
Mongoid::Errors::DocumentNotFound:
Problem:
Document not found for class Client with attributes {:auth_id=>"7123"}.
Note that if I use @clients = Fabricate.times(1, :client) (which means fabricate only one client) it works perfectly. So I think that the problem is in DatabaseCleaner (I tried many configurations, but all unsuccessfully).
I'm using Ruby 2.2.0, Rails 4.2.0 (rails-api, to be exact), DatabaseCleaner 1.4.1, Mongoid 4.0.2 and Fabrication 2.13.1
Do you have any idea on how to fix that? Thanks.
This looks like it might be an issue with your test setup and when database_cleaner is being executed. Typically one would set it up to encapsulate each example run individually, not as before and after :all.
However, if you are only using it to clean out your mongoid documents I think you could just ditch it entirely. Fabrication runs this before each example in its own test suite. You may want to give that a try instead.
Mongoid::Config.purge!https://github.com/paulelliott/fabrication/blob/master/spec/support/mongoid.rb#L5