Dependent Attributes in Factory Girl

It seems like I should have found the obvious answer to this problem a few hours after Google and testing.

I want to be able to set caredate.user_id => provider.user_id in a caredate factory.

Test Error:

ActiveRecord :: RecordInvalid: Verification failed: user must be the same as provider user

I have an ActiveRecord check that works when checking through a 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

I apologize if an answer was given earlier; I tried several different options and could not get it to work.

Update: This is being tested, so I'm getting closer. I could hack a random number.

Factory.define :caredate do |f| 
  f.association :user, :id => 779
  f.association :provider, :user_id => 779
end
+5
2
Factory.define :caredate do |f|
  provider = Factory.create(:provider)
  f.provider provider
  f.user provider.user
end
+6

user_id after_create after_build:

Factory.define :caredate do |f|
  f.after_create { |caredate| caredate.user_id = caredate.provider.user_id }
end
0

All Articles