ruby-on-rails - 产品型号为 : Rspec tell me that "Trait not registered" 的 FactoryGirl

标签 ruby-on-rails rspec factory-bot

嗨魔法社区!

对于那些有时间的人来说,仍然是一个新手,有一些基本问题;-)

我像这样创建了一个用户模型和一个产品模型(感谢@grotori):

class User
  has_many :owned_products, class_name: "Product", foreign_key: "owner_id"
  has_many :borrowed_products, class_name: "Product", foreign_key: "borrower_id"
end

class Product
    belongs_to :owner, class_name: "User", foreign_key: "owner_id"
    belongs_to :borrower, class_name: "User", foreign_key: "borrower_id"
end

然后我使用 FactoryGirl 创建了一个 factories.rb,如下所示:

FactoryGirl.define do

  factory :user do
    sequence(:name) { |n| "Person #{n}" }
    sequence(:email) { |n| "Person_#{n}@example.com" }
    password "kaboum"
    password_confirmation "kaboum"
  end

  factory :product do
    name "Product"
    owner
    borrower
  end
end

为了像这样测试 dependent::destroy 条件:

describe User do

  before do
    @user = User.new(name: "Example User",
                        email: "user@example.com",
                        password: "kaboum",
                        password_confirmation: "kaboum")
  end

  describe "product associations" do
    before { @user.save }
    let!(:product) { FactoryGirl.create(:product, owner: @user) }

    it "should destroy associated product" do
      product_to_be_destroyed = @user.owned_products.first
      @user.destroy
      expect(product_to_be_destroyed).not_to be_empty
      expect(Product.where(id: product_to_be_destroyed.id)).to be_empty
    end
  end
end

Rspec 给我答案 ArgumentError: Trait not registered: owner

我搜索了 already answered questions在 stackoverflow 上,但我无法解决我的问题。一种解决方案是为我的 factories.rb 中的“所有者”或“借款人”字段分配一个默认值,但我不希望这样,这根据 FactoryGirl help 是可能的。 .

我们将不胜感激:-)

最佳答案

我相信这可以在不创建额外的所有者和借用者工厂的情况下解决:

  factory :product do
    name "Product"
    association :owner, factory: :user
    association :borrower, factory: user
  end

关于ruby-on-rails - 产品型号为 : Rspec tell me that "Trait not registered" 的 FactoryGirl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16559176/

相关文章:

ruby-on-rails - 尝试加载 gem 'factory_girl_rails' 时出错。 ( bundler ::GemRequireError)

ruby-on-rails - 更改用于生成 Rails 应用程序文档的 RDoc 模板

ruby-on-rails - RSpec 请求规范发布一个空数组

ruby-on-rails - RSpec 测试索引 View 和 will_paginate

ruby-on-rails - 如何在不破坏 FactoryGirl 的情况下将 seeds.rb 加载到测试数据库中?

ruby-on-rails - "scoped"查询的事件管理员过滤器

html - RoR3/HTML : Many check boxes, 对那些检查项目的不同操作,如何?

rspec - 在rSpec和Rails3中 stub 设计

ruby - Test::Unit 是否仍然与 Rails 相关?

ruby-on-rails - 工厂女是干什么用的?为您设置对象?