Dependent Attributes in Factory Girl
Asked Answered
E

2

7

Seems like I should have been able to find an obvious answer to this problem after a few hours of Googling and testing.

I want to be able to set caredate.user_id => provider.user_id within the caredate factory.

Test Error:

ActiveRecord::RecordInvalid: Validation failed: User must be same as provider user

I have an ActiveRecord validation which works when tested via the browser:

class Caredate < ActiveRecord::Base //works fine when testing via browser
  belongs_to :user
  belongs_to :provider

  validates_presence_of :user_id
  validates_presence_of :provider_id
  validate :user_must_be_same_as_provider_user

  def user_must_be_same_as_provider_user
    errors.add(:user_id, "must be same as provider user") unless self.user_id == self.provider.user_id
  end

end

//factories.rb
Factory.define :user do |f| 
  f.password "test1234"
  f.sequence(:email) { |n| "foo#{n}@example.com" }
end

Factory.define :caredate do |f| 
  f.association :provider
  **f.user_id { Provider.find_by_id(provider_id).user_id }  //FAILS HERE**
end

Factory.define :provider do |f| 
  f.association :user
end

My apologies if this has been answered previously; I tried several different options and couldn't get it to work.

Update: This passes validation, so I'm getting closer. I could hack with a random number.

Factory.define :caredate do |f| 
  f.association :user, :id => 779
  f.association :provider, :user_id => 779
end
Erector answered 10/12, 2010 at 16:13 Comment(0)
A
8
Factory.define :caredate do |f|
  provider = Factory.create(:provider)
  f.provider provider
  f.user provider.user
end
Ate answered 11/12, 2010 at 2:4 Comment(2)
The order dependency is a good point, and it's even worse if the two factories are defined in separate files. At some point you wonder whether it makes more sense to use fixtures in cases like this.Ate
This worked until I tried to rebuild db and load schema. Looks like FactoryGirl is looking for table. rake db:schema:load --trace ... rake aborted! Table 'claimaway_development.providers' doesn't exist Here is a discussion but I couldn't get this solution to work.Erector
L
0

Try setting the user_id in after_create or after_build:

Factory.define :caredate do |f|
  f.after_create { |caredate| caredate.user_id = caredate.provider.user_id }
end
Leitmotiv answered 10/12, 2010 at 19:11 Comment(1)
I'm assuming you mean modify existing :caredate Factory, otherwise I get an error for multiple :caredate factories. Unfortunately isn't working either. I believe the validation will fail when it attempts to save the object, so it never reaches the "after_create" stage. Thanks for the suggestion, though. I'm continuing to try things.Erector

© 2022 - 2024 — McMap. All rights reserved.