RSpec:FactoryBot看到重复的定义

时间:2018-03-31 15:25:44

标签: ruby-on-rails rspec factory-bot rspec-rails

我还是新手使用FactoryBot所以我可能会遗漏一些东西。我收到此错误消息: enter image description here

是否可能是由于spec_helper.rb文件中的设置不当造成的?

至于定义user.rb工厂,我尝试了包括" association:contract"在user.rb文件中。我仍然不确定我是否应该这样做,或者目前的格式是否适合Rspec获取与contract.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|

规格/工厂/ users.rb的

FactoryBot.define do
  factory :user do
    full_name "Test tester"
    email "test@tester.com"
    password "123456"
  end
end

规格/工厂/ contracts.rb

FactoryBot.define do
  factory :contract do
    vendor "O2"
    starts_on "2019-03-08"
    ends_on "2019-03-10"
    price 30
  end
end

规格/请求/ contracts_api_spec.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

1 个答案:

答案 0 :(得分:1)

我相信您不需要在 spec_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)