chandradot99
chandradot99

Reputation: 3866

How to configure database_cleaner with rails

I have some services inside my app/services folder.Now I want to test these services, so I am using rspec and factorygirl. I am creating user with factoryGirl, but when i am running rspec it is showing me following error

 Failure/Error: @user ||= FactoryGirl.create(:user)

 ActiveRecord::RecordInvalid:
   Validation failed: Email has already been taken

I am using database_cleaner gem to clean the database after each test. Below is my config file

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?

require 'spec_helper'
require 'rspec/rails'
require 'factory_girl_rails'
require 'database_cleaner
ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|

  config.include FactoryGirl::Syntax::Methods

  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.include Devise::TestHelpers, type: :controller

  config.use_transactional_fixtures = false

  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end


  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!

end

I don't know where i am going wrong.

Upvotes: 2

Views: 1198

Answers (1)

born4new
born4new

Reputation: 1687

You need to specify the strategy to use between each specs (transaction is a safe choice here):

RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end
end

Upvotes: 3

Related Questions