版本:
数据库清洁器和FactoryBot.lint在support/factory_bot.rb
中一起运行
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with :truncation
begin
DatabaseCleaner.start
FactoryBot.lint strategy: :build unless config.files_to_run.one?
ensure
DatabaseCleaner.clean
end
end
end
运行bin/rspec
将返回以下错误:
jathayde$ bin/rspec
An error occurred in a `before(:suite)` hook.
Failure/Error: FactoryBot.lint strategy: :build unless config.files_to_run.one?
FactoryBot::InvalidFactoryError:
The following factories are invalid:
* project - Validation failed: Name has already been taken (ActiveRecord::RecordInvalid)
# ./spec/support/factory_bot.rb:10:in `block (2 levels) in <main>'
Finished in 0.60158 seconds (files took 2.66 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples
这是项目工厂:
FactoryBot.define do
factory :project do
sequence(:name) { |n| "Project-#{n}"}
short_name { name.downcase.gsub(/[\s&\/]+/, "-") }
association :category
association :client
page_title { name }
meta_description "my text description"
end
end
下面是models/project.rb
文件:
class Project < ApplicationRecord
extend FriendlyId
friendly_id :slug, use: [:slugged, :finders]
belongs_to :client
belongs_to :category
validates :name, presence: true
validates :short_name, presence: true,
uniqueness: true
validates :category, presence: true
validates :client, presence: {
on: :create,
message: "Must have a client for a project" }
validates :page_title, presence: true
before_validation :set_slug
private
def set_slug
self.slug = "#{name}".parameterize
end
end
其他说明:
uniqueness: true
是否位于模型文件中的short_name
上,都会发生这种情况。{Faker::Name.name}
作为项目名称(没有序列),也会发生这种情况。发布于 2018-01-09 16:05:16
原来这是category
协会,而不是project
本身--这才是问题所在。类别工厂:
FactoryBot.define do
factory :category do
name "Name"
short_name { Faker::Lorem.word }
description { Faker::Lorem.paragraph }
end
end
更改为此解决了以下问题:
FactoryBot.define do
factory :category do
name { Faker::Name.name }
short_name { Faker::Lorem.word }
description { Faker::Lorem.paragraph }
end
end
https://stackoverflow.com/questions/48171478
复制相似问题