Jan Dudek
Jan Dudek

Reputation: 807

factory_girl's Cucumber steps and optional associations

I have the following models:

class Person < ActiveRecord::Base
  belongs_to :family
end

class Family < ActiveRecord::Base
end

And the following factories:

Factory.define :person do |p|
  p.association :family
end

Factory.define :family do |f|
end

And I'm using factory_girl's Cucumber steps, like this:

Given the following people exist:
  | First name | Last name |
  | John       | Doe       |

Given the following people exist:
  | First name | Last name | Family             |
  | John       | Doe       | Name: Doe's family |

I'd like to create people without associated families using the first form, and the latter to create people with families. Now every person has a family. In fact, using the first form fails, because I have also validates_presence_of :name in Family class.

If I remove p.association :family from Person factory definition, the latter form fails, because it tries to set string as associated record (it runs something like family = "Name: ...").

Is it possible to have optional associations in Cucumber steps defined by factory_girl?

Upvotes: 2

Views: 932

Answers (2)

Keith Gaddis
Keith Gaddis

Reputation: 4113

I'd make your default person sans-association, then define a child factory that adds the association, which may be a little counter-intuitive but is the proper way to build up the class hierarchy:

Factory.define(:person) do |f|

end

Factory.define(:family_member, :parent => :person) do |f|
  f.association(:family)
end

Upvotes: 1

Dan Croak
Dan Croak

Reputation: 1669

I'd create another factory like:

Factory.define :orphan, :class => "Person" do |factory|
  # does not belong to a family
end

Then use that in your first setup:

Given the following orphans exist:
  | First name | Last name |
  | John       | Doe       |

Upvotes: 3

Related Questions