Skip to content

Instantly share code, notes, and snippets.

@davidjrice
Forked from gwik/gist:6298001
Created October 30, 2015 12:59
Show Gist options
  • Save davidjrice/3d923a6920d80dad7b22 to your computer and use it in GitHub Desktop.
Save davidjrice/3d923a6920d80dad7b22 to your computer and use it in GitHub Desktop.
Database setup and seeds for Rails, RSpec, Capybara, DatabaseCleaner and friends
# Database setup and seeds loading
# See the block post : http://sigkill.tumblr.com/post/58933579738/test-database-setup-and-seeds-with-rails-rspec
module Seeder
@@__cache__ = {}
def self.load_seed(filename, prefix='app')
filename = Rails.root + "db/seeds/#{prefix}/#{filename}.seeds.rb"
seed_mod = @@__cache__[filename] ||= begin
mod = Module.new
buf = "def self.seed!"
buf << File.read(filename)
buf << "end"
mod.module_eval(buf)
mod
end
seed_mod.seed!
end
end
# Don't get confused by this module it is just there because
# DatabaseCleaner is not able to tell what the current strategy
# is (DatabaseCleaner.strategy won't work [sigh..])
module Strategy
def self.set(value)
DatabaseCleaner.strategy = @strategy = value
@strategy
end
def self.get
@strategy
end
def self.truncation?
@strategy == :truncation
end
def self.transaction?
@strategy == :transaction
end
end
# load all the seeds you need
def load_seeds
Seeder.load_seed('configuration', 'test')
Seeder.load_seed('categories')
end
RSpec.configure do |config|
config.use_transactional_fixtures = false
config.before(:suite) do
Strategy.set :transaction
DatabaseCleaner.clean_with :truncation
load_seeds
end
config.before(:each) do
# differenciate between features and other kinds of examples
if example.metadata[:type] == :feature
# if previous example was already a transation we
# don't need to reload the seeds
load_seeds unless Strategy.transaction?
Strategy.set :truncation
else
# strategy was previously transaction, the seeds are already there
load_seeds if Strategy.truncation?
Strategy.set :transaction
end
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment