Created
August 17, 2016 13:19
-
-
Save duffyjp/c89aee6c32f1fd06ad5a44f6c5858cd6 to your computer and use it in GitHub Desktop.
Rspec test to verify all Rails models have a FactoryGirl factory, and that each factory creates a valid model instance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# FactoryGirl factory verifier | |
# Jacob Duffy | |
# https://github.com/duffyjp | |
# | |
# Starts with all table names, then finds all models using each table. | |
# Verifies each model has a factory and that it is able to save! | |
require 'rails_helper' | |
describe "Factory" do | |
# Make sure Rails knows about all of its models | |
Rails.application.eager_load! | |
(ActiveRecord::Base.connection.tables - ["schema_migrations", "versions"]).each do |table| | |
ActiveRecord::Base.descendants.select{|d| d.table_name == table && !(d.to_s =~ /HABTM/)}.each do |model| | |
factory = model.name.tableize.parameterize("_").singularize.to_sym | |
it "for #{model} creates a #{model}" do | |
expect(build(factory)).to be_an_instance_of model | |
end | |
it "for #{model} creates a valid object" do | |
expect{build(factory).save!}.to_not raise_error | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this to your spec/models/ folder to ensure all models have valid factories. This includes all STI models that share a table.