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
Factory.define :caredate do |f|
  provider = Factory.create(:provider)
  f.provider provider
  f.user provider.user
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With