Ruby on rails RSpec:FactoryBot看到重复的定义

Ruby on rails RSpec:FactoryBot看到重复的定义,ruby-on-rails,rspec,factory-bot,rspec-rails,Ruby On Rails,Rspec,Factory Bot,Rspec Rails,我对使用FactoryBot还不熟悉,所以我可能遗漏了一些东西。我收到以下错误消息: 这可能是由于spec_helper.rb文件中的设置不正确造成的吗 至于定义user.rb工厂,我尝试在user.rb文件中包含“associations:contracts”。我仍然不确定我是否应该这样做,或者Rspec是否可以使用这种当前格式来获取与contracts.rb的关联 感谢您的帮助!谢谢 spec_helper.rb require 'factory_bot_rails' RSpec.conf

我对使用FactoryBot还不熟悉,所以我可能遗漏了一些东西。我收到以下错误消息:

这可能是由于spec_helper.rb文件中的设置不正确造成的吗

至于定义user.rb工厂,我尝试在user.rb文件中包含“associations:contracts”。我仍然不确定我是否应该这样做,或者Rspec是否可以使用这种当前格式来获取与contracts.rb的关联

感谢您的帮助!谢谢

spec_helper.rb

require 'factory_bot_rails'
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
  FactoryBot.definition_file_paths = [File.expand_path('../factories', __FILE__)]
  FactoryBot.find_definitions
  # rspec-expectations config goes here. You can use an alternate
  # assertion/expectation library such as wrong or the stdlib/minitest
  # assertions if you prefer.
  config.expect_with :rspec do |expectations|
spec/factories/users.rb

FactoryBot.define do
  factory :user do
    full_name "Test tester"
    email "test@tester.com"
    password "123456"
  end
end
spec/factories/contracts.rb

FactoryBot.define do
  factory :contract do
    vendor "O2"
    starts_on "2019-03-08"
    ends_on "2019-03-10"
    price 30
  end
end
规范/请求/合同\u api\u规范rb

require 'rails_helper'

RSpec.describe "ContractsApi", type: :request do

  describe "POST #create" do
    before(:each) do
      @user = FactoryBot.create(:user)
      @current_user = AuthenticateUserCommand.call(@user.email, @user.password)
      @contract = @current_user.contracts.create(vendor: "Lebara", starts_on: "2018-12-12", ends_on: "2018-12-14", price: "15")
    end


    it 'creates a new contract' do
      expect { post api_v1_contracts_path, params: @contract }.to change(Contract, :count).by(1)
    end
  end
end

我相信您不需要在spec\u helper.rb中配置FactoryBot,您在那里所做的工作可能会导致FactoryBot加载工厂两次

尝试将spec_helper.rb的内容更改为:

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods

  # rspec-expectations config goes here. You can use an alternate
  # assertion/expectation library such as wrong or the stdlib/minitest
  # assertions if you prefer.
  config.expect_with :rspec do |expectations| 

另外,考虑到您正在包括
FactoryBot::Syntax::Methods
,在测试中,您可以简单地使用
@user=create(:user)
而不是
@user=FactoryBot.create(:user)

我按照您的建议做了,现在我收到了错误消息:ArgumentError:Factory not registered:contracts?你认为这个协会没有被接受吗?我同意你的观点,你不知何故需要两次这些文件。您可以尝试通过在其中一个factory文件的第一行中放置“here I load factory X”
来调试它,并查看它是否显示两次。然后,您可以尝试获取回溯并查看从何处加载。嘿@MLZ您是否有任何其他代码正在使用
FactoryBot.create(:contracts)
?错误消息表明您正在尝试创建
FactoryBot.create(:contracts)
而不是
FactoryBot.create(:contract)
(单数)Mike和Rafael,感谢您的参与。为了简单起见,我现在决定使用PORO,但稍后可能会再讨论这个问题。