ruby-on-rails - 工厂女工的依赖属性

标签 ruby-on-rails unit-testing testing factory-bot

经过几个小时的谷歌搜索和测试,我似乎应该能够找到这个问题的明显答案。

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

测试错误:

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

我有一个 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

如果之前已经回答过这个问题,我深表歉意;我尝试了几种不同的选择,但无法正常工作。

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

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

关于ruby-on-rails - 工厂女工的依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4410854/

相关文章:

ruby-on-rails - 在没有任何错误消息的情况下在 Heroku 上调试 500 错误

c# - 使用 Moq 设置 Mock 存储库

performance - 如何验证我的 LoadRunner 测试脚本是否确实在执行?

testing - 如何使用 Jest 或其他 Javascript 测试框架测试 console.log 输出?

ruby-on-rails - 使用 Nokogiri 保留换行符

ruby-on-rails - Rails 可以像 Phoenix 管道一样为指定路由指定中间件

ruby-on-rails - 收到 Vagrant 的这个奇怪错误,想知道是否有人可以伸出援手

c# - 在 FakeDbSet 实现中伪造 find 方法

javascript - Ember 单元测试渲染 Handlebars 返回 null 或 undefined

ios - NSObject 在 StoryBoard/Interface Builder 中的作用是什么?