ruby-on-rails - 使用 Factory_girl 建立测试中关联

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

我希望能够仅在每个特定测试中创建与 ID 的关联,尽量避免在工厂中定义它们。 我一直在关注Rails 4 Test Prescriptions

Avoid defining associations automatically in factory_girl definitions. Set them test by test, as needed. You’ll wind up with more manageable test data.

class Workspace < ActiveRecord::Base
  has_many :projects
end
class Project < ActiveRecord::Base  
  belongs_to :workspace
end 

这就是我想要的

test "" do
 project_with_id = build_stubbed(:project)
 workspace_with_id = build_stubbed(:workspace)
 workspace_with_id.projects.push(project_with_id)
end 

我正在使用 build_stubbed 创建有效 ID,这会出现以下错误:

*** RuntimeError Exception: stubbed models are not allowed to access the database - Project#save({:validate=>true})

于是,读厂妹的documentation我想出了工作协会,但我不想在工厂里定义它们,甚至没有特征。

FactoryGirl.define do
  factory :project do
    association :workspace, strategy: :build_stubbed
  end
end 

test "" do
 project = build_stubbed(:project)
end 

这是有效的,因为我可以调用 project.workspace,并且两者都有一个有效的 ID

如何创建有效的关联(带 ID),但不接触数据库,仅使用 Factory girl 创建独立对象?

最佳答案

如果你正在使用 Rspec,你可以做这样的事情

 let!(:user1) { FactoryGirl.create(:user) }
 let!(:user_social_profile1) { FactoryGirl.create(:user_social_profile, user_id: user1.id) }

也在 Rspec

let!(:user1) { FactoryGirl.create(:user) }
let!(:user_social_profile1) { FactoryGirl.create(:user_social_profile, user: user1) }

我相信在 minitest/test_unit 中

user1 = FactoryGirl.create(:user)
user_social_profile1 = FactoryGirl.create(:user_social_profile, user_id: user1.id)

很抱歉,我没有解释与工厂协会一起使用 build_stubbed 的相关问题,this答案很好地解释了这一点。

关于ruby-on-rails - 使用 Factory_girl 建立测试中关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40228976/

相关文章:

ruby-on-rails - 设计不显示登录错误消息

ruby-on-rails - Rspec expect( ) 与 expect { }

ruby - 在运行时获取/设置 Ruby 方法元数据的最佳策略是什么?

c# - 常见项目的存储库模式

java - 在测试中实例化多个 Spring Boot 应用程序

javascript - 如何测试 Angular mat-nav-list 是否包含元素?

javascript - cookie 的 Rails 编码与 JavaScript decodeURIComponent 不兼容

mysql - 考虑到性能,如何设计允许每个用户一票的评级系统?

ruby - 在两个单独的页面上抓取需要登录用户名和密码的站点

ruby-on-rails - rails geokit - 获取旅行/通勤时间