Skip to content

Instantly share code, notes, and snippets.

@drueck
Created May 6, 2014 06:07
Show Gist options
  • Save drueck/11554143 to your computer and use it in GitHub Desktop.
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
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
@drueck
Copy link
Author

drueck commented May 6, 2014

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.

@george-carlin
Copy link

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