Rails: access test fixtures from factories?
Asked Answered
I

1

11

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
Ingraham answered 2/10, 2015 at 23:5 Comment(2)
If you're not aware, you can load that record (assuming the fixture has already been loaded) with 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...Menis
Hmm, that's an interesting idea. I was able to get it to work just by using User.first, too, but I was hoping to avoid using a database query. I was sort of assuming users(:active) has an in memory copy, but I should probably verify that.Ingraham
M
0

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
Madelene answered 9/2, 2023 at 2:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.