我对使用 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|
规范/工厂/用户.rb
FactoryBot.define do
factory :user do
full_name "Test tester"
email "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e99d8c9a9da99d8c9a9d8c9bc78a8684" rel="noreferrer noopener nofollow">[email protected]</a>"
password "123456"
end
end
规范/工厂/契约(Contract).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
最佳答案
我相信您不需要在 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)
关于ruby-on-rails - RSpec:FactoryBot 看到重复的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49589355/