Is there a way I can access test fixtures from within my factories? I'm trying to do something like:
Factory.define do
factory :foo do
user { users(:active) }
end
end
Is there a way I can access test fixtures from within my factories? I'm trying to do something like:
Factory.define do
factory :foo do
user { users(:active) }
end
end
You can access fixtures in your factories using the ActiveRecord::FixtureSet class, which provides access to the fixtures defined in your test/fixtures directory. You could access the :active user fixture like this:
FactoryBot.define do
factory :foo do
user { ActiveRecord::FixtureSet.cached_fixtures[:active, 'users'] }
end
end
IMO the use of fixtures in factories is discouraged, as it couples your factories to your tests and makes it difficult to reuse your factories in other contexts. A better approach would be to create a factory for the User model with an active trait and use that within your :foo factory
FactoryBot.define do
factory :user do
trait :active do
active { true }
end
end
factory :foo do
user { create(:user, :active) }
end
end
© 2022 - 2024 — McMap. All rights reserved.
User.find(ActiveRecord::FixtureSet.identify(:active))
. Not sure if that will actually get you any closer (or if this is even a good idea), though... – MenisUser.first
, too, but I was hoping to avoid using a database query. I was sort of assumingusers(:active)
has an in memory copy, but I should probably verify that. – Ingraham