工厂女孩的依赖属性

Kev*_*alt 7 testing unit-testing ruby-on-rails factory-bot

看起来好像我应该能够在谷歌搜索和测试几个小时后找到这个问题的明显答案.

我希望能够在caredate工厂中设置caredate.user_id => provider.user_id.

测试错误:

ActiveRecord :: RecordInvalid:验证失败:用户必须与提供者用户相同

我有一个ActiveRecord验证,通过浏览器测试时有效:

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
Run Code Online (Sandbox Code Playgroud)

如果以前已经回答过,我很抱歉; 我尝试了几种不同的选择,无法让它发挥作用.

更新:这通过验证,所以我越来越近了.我可以用一个随机数来破解.

Factory.define :caredate do |f| 
  f.association :user, :id => 779
  f.association :provider, :user_id => 779
end
Run Code Online (Sandbox Code Playgroud)

zet*_*tic 8

Factory.define :caredate do |f|
  provider = Factory.create(:provider)
  f.provider provider
  f.user provider.user
end
Run Code Online (Sandbox Code Playgroud)