-
Clone down this repo:
git clone https://github.com/lao9/factory_girl_spike.git
-
Check out exercise branch to practice setup and obstacle course:
git checkout factory-girl-skate-park
-
Update Gemfile:
group :development, :test do
...
gem 'database_cleaner'
gem 'factory_girl_rails'
gem 'faker'
gem 'launchy'
gem 'shoulda-matchers'
end
-
Don't forget to bundle!
bundle install
-
Configure DatabaseCleaner
In rails_helper.rb
find the line config.use_transactional_fixtures = true
and
change true
to false
. If you are curious what this does, look here
In your console: mkdir spec/support
And then: touch spec/support/database_cleaner.rb
This is where you will put your DatabaseCleaner configuration for RSpec.
Open that file and add the code :
RSpec.configure do |config|
config.before(:suite) do
begin
DatabaseCleaner.start
FactoryGirl.lint
ensure
DatabaseCleaner.clean_with(:truncation)
end
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, :js => true) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
If you would like an explanation of what each line of code in this file does, look here and here
Finally, look in rails_helper.rb
, find the line:
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
and uncomment it. This will allow rails to find all the the files in your newly created spec/support
directory.
Configuring FactoryGirl
touch spec/support/factory_girl.rb
Open that file and write:
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end
Configuring Should-Matchers
Open rails_helper.rb
and place this code at the bottom of the file.
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
Setup Database
rake db:setup
Once all set, we'll walk through how to replace our current model tests on this branch with factories for the setup and shoulda-matchers for attribute and relationship validation.