Skip to content

Instantly share code, notes, and snippets.

@duffyjp
Created August 17, 2016 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duffyjp/c89aee6c32f1fd06ad5a44f6c5858cd6 to your computer and use it in GitHub Desktop.
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
# 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
@duffyjp
Copy link
Author

duffyjp commented Aug 17, 2016

Add this to your spec/models/ folder to ensure all models have valid factories. This includes all STI models that share a table.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment