Created
May 6, 2014 06:07
-
-
Save drueck/11554143 to your computer and use it in GitHub Desktop.
Variation of Corey Haines' active_record_spec_helper.rb that supports FactoryGirl, Shoulda and MoneyRails
This file contains 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
require "simplecov" | |
SimpleCov.start "rails" | |
require "yaml" | |
require "active_record" | |
require "factory_girl_rails" | |
require "shoulda-matchers" | |
require 'money-rails' | |
connection_info = YAML.load_file("config/database.yml")["test"] | |
ActiveRecord::Base.establish_connection(connection_info) | |
MoneyRails::Hooks.init | |
RSpec.configure do |config| | |
config.include FactoryGirl::Syntax::Methods | |
config.before(:suite) do | |
FactoryGirl.factories.clear | |
FactoryGirl.find_definitions | |
end | |
config.around do |example| | |
ActiveRecord::Base.transaction do | |
example.run | |
raise ActiveRecord::Rollback | |
end | |
end | |
end |
Loading all Factory definitions with FactoryGirl.find_definitions
didn't work for me as it requires all my models to be loaded... e.g. if I'm testing the model Post
I'll only require 'post'
and not require all my other models, but then FactoryGirl will crash because it will try to load e.g. the factory users
and fail because it can't find the definition of User
.
My solution is just to forget about factory definitions within active_record_spec_helper
and load them manually within the individual model spec files. Here's an example:
require "active_record_spec_helper"
require "friendly_id"
require "email"
require "factories/emails"
describe Email do
.
.
.
end
I'm still having issues with my associations as described in this StackOverflow question - upvotes are available!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by this article by Corey Haines on Speeding up ActiveRecord Tests, I decided to try to implement this in one of my codebases. I quickly found that in many of my ActiveRecord model specs I needed support for FactoryGirl factories, Shoulda matchers and MoneyRails. The first two were fairly simple. It took me a while to figure out how to get MoneyRails support initialized.
I'm still not sure if this is ideal, especially how I'm dealing with clearing and re-discovering the factory definitions. If you come across this and have any suggestions for improvement, I'd love to hear them.