firedev
firedev

Reputation: 21088

How to extract FactoryGirl traits in a separate file

I have a bunch of factories that share a common trait:

trait :with_images do
  after(:create) do |resource|
    resource.images << FactoryGirl.create(:image, imageable: resource)
    resource.enabled = true
    resource.save
  end
end

I would like to extract it in a separate file but not 100% sure how to arrange it.

Upvotes: 1

Views: 459

Answers (1)

Tiago Farias
Tiago Farias

Reputation: 3407

Traits can be defined globally, so then you can use them in another factory you like. You could create a new file inside spec/factories, like, spec/factories/traits.rb or something:

And define your global traits:

FactoryGirl.define do
  trait :complete do
    complete false
  end
end

And then you would have in another file, say spec/factories/user.rb, a different factory using this trait:

FactoryGirl.define do
  factory :user do
    complete
  end
end

I'm just not sure if that's a good idea, I mean, I think it should be visible right away that a trait is kind of a complement of a given factory. It is very clean, but not so readable.

Upvotes: 1

Related Questions