Meltemi
Meltemi

Reputation: 38359

Factory_girl: one attribute's definition is dependent upon another one

How can you build a factory where one attribute is dependent upon the other?

  factory :event do
    sequence(:title) { |n| "Event #{n}" }
    sequence(:description) { |n| "More detailed info about event #{n}" }
    start_at { rand(1..100).days.from_now }
    end_at { start_at + rand(1..5).hours }   # <=== referencing start_at
  end

Using this gives a NameError: uninitialized constant Event my specs and I assume it's from trying to set end_at to a value dependent upon value of start_at. How to do this? Trying to instantiate a few dozen valid "events". Thanks.

Upvotes: 1

Views: 157

Answers (3)

David Lowenfels
David Lowenfels

Reputation: 997

this is described here https://thoughtbot.github.io/factory_bot/dependent-attributes/summary.html

your syntax was correct but your error was because the gem couldn't find the Event model. unrelated to dependent attributes, as you subsequently discovered.

Upvotes: 1

Robin
Robin

Reputation: 915

I think what you want to do is something like this:

factory :event do
  title 'foo'
  description "bar"
  other_attributes "baz"

  factory :dynamic_event do
    sequence(:title) { |n| "Event #{n}" }
  end

end

The :dynamic_event factory will inherit all attributes from the event factory, but overrides that ones given inside its block. (The titlein a sequence in this example)

Upvotes: -1

Robin
Robin

Reputation: 915

The error does not occur because of something wrong inside your factory block. The Event class is not defined correctly.

Could you please show your Event model?

Perhaps its nested in a module? Then you could do this:

factory :event, :class => 'ModuleName::Event' do
  ...
end

Upvotes: 0

Related Questions