版本:
数据库清理程序和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}
作为项目名称(没有序列)答案 0 :(得分:0)
原来这是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