RSpec FactoryBot.lint在排序的工厂名称上失败

时间:2018-01-09 15:27:01

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

版本:

  • Rails 5.2.0.beta2
  • ruby​​ 2.4.2p198(2017-09-14修订版59899)[x86_64-darwin17]
  • rSpec 3.7.0

数据库清理程序和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}作为项目名称(没有序列)
  • ,也会发生这种情况

1 个答案:

答案 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