嗨神奇的社区!
对于那些有时间的人来说,仍然是一个有基本问题的新手;-)
我创建了这样的用户模型和产品模型(感谢@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 创建一个 factory.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
。
我在stackoverflow上搜索了已经回答的问题,但我无法解决我的问题。一种解决方案是为我的 factory.rb 中的“所有者”或“借款人”字段分配一个默认值,但我不希望这样,这可以根据FactoryGirl 帮助进行。
任何帮助将不胜感激:-)