工厂机器人错误 "private method `new' called for User:Class (NoMethodError)"

Factory bot error "private method `new' called for User:Class (NoMethodError)"

我是 factory bot 的新手,我尝试使用 factory bot 创建样本数据,但出现此错误

如何解决这个错误?

features/support/factories.rb:

require 'factory_bot'


FactoryBot.define do
  factory :user do
    email "xxx123@xyz.co"
    password "asdf123"
    password_confirmation "asdf123"
  end
end
FactoryBot.define do
  factory :post do
    user = FactoryBot.create(:user)
  end
end

需要'factory_bot'

FactoryBot.define do
  factory :user do
    email "xxx123@xyz.co"
    password "asdf123"
    password_confirmation "asdf123"
  end
end

FactoryBot.define do
  factory :post do
    user
  end
end

FactoryBot 文档中所述

Associations

It's possible to set up associations within factories. If the factory name is the same as the association name, the factory name can be left out.

factory :post do
  # ...
  author
end

You can also specify a different factory or override attributes:

factory :post do
  # ...
  association :author, factory: :user, last_name: "Writely"
end