greenif
greenif

Reputation: 1093

Ruby gem Factory Bot:

My goal is to create a factory with a few fields with the same value, for example I want that name and full_name be equal.

FactoryBot.define do
  factory :brand do
    n = Faker::Company.name
    name      { n }
    full_name { n }
  end
end

The above approach doesn't work, because n get value only one time.

So, how to eval some block to share its data with a few dynamic fields?


Another case: I have YML file with brands, and method get_random_brand which returns hash with brands fields:

FactoryBot.define do
  factory :brand do
    b = get_random_brand
    name      { b['name'] }
    full_name { b['full_nam'] }
  end
end

I understand that factory do when the factory definition is read.

How to evaluate get_random_brand only ones per each factory created?

Upvotes: 0

Views: 67

Answers (1)

max
max

Reputation: 102240

Dependent attributes are actually really simple in FactoryBot as you just call the method for the other attribute in the block:

FactoryBot.define do
  factory :brand do
    name      { Faker::Company.name }
    full_name { name }
  end
end

You can for example do:

FactoryBot.define do
  factory :user do
    name  { Faker::Name.name }
    email { name.downcase.tr(' ', '.') + "@example.com" }
  end
end

The above approach doesn't work, because n get value only one time.

Thats because the factory ... do block is evaluated when the factory definition is read. Not every time the factory is used.

Upvotes: 2

Related Questions