开发者

Dependent Attributes in Factory Girl

开发者 https://www.devze.com 2023-01-29 17:48 出处:网络
Seems like I should have been able to find an obvious answer to this problem after a few hours of Googling and testing.

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 :cared开发者_StackOverflowate 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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号