Skip to content

Instantly share code, notes, and snippets.

@alpaca-tc
Created May 23, 2021 12:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alpaca-tc/ab80f0c5233068d3266548df87acda59 to your computer and use it in GitHub Desktop.
Save alpaca-tc/ab80f0c5233068d3266548df87acda59 to your computer and use it in GitHub Desktop.
FactoryBotの定義漏れ、不正な定義をテストする
# frozen_string_literal: true
RSpec.describe FactoryBot do
shared_examples_for 'valid definition' do
it 'is valid' do
is_expected.to be_valid, (-> { factory.errors.full_messages.join("\n") })
end
end
FactoryBot.factories.map(&:name).each do |factory_name|
describe "factory :#{factory_name}" do
subject(:factory) { FactoryBot.build(factory_name, *options) }
let(:options) { [] }
it_behaves_like 'valid definition'
# Test each trait
FactoryBot.factories[factory_name].definition.defined_traits.map(&:name).each do |trait_name|
context "with trait :#{trait_name}" do
let(:options) { [trait_name] }
it_behaves_like 'valid definition'
end
end
end
end
describe 'Definitions' do
def factory_defined?(name)
FactoryBot.factories[name]
true
rescue ArgumentError, KeyError
false
end
it 'completes definitions' do
table_names = ApplicationRecord.connection.tables
missing_factories = table_names.reject do |table_name|
factory_name = table_name.to_s.singularize.to_sym
factory_defined?(factory_name)
end
expect(missing_factories).to be_empty, -> { "Missing factory definition. #{missing_factories.map(&:to_sym)}" }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment