Last active
June 10, 2021 18:56
-
-
Save RobinDaugherty/9f4e5f782d9fdbe191a23de30ad8b539 to your computer and use it in GitHub Desktop.
Rspec with DatabaseCleaner
This file contains hidden or 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
# spec/support/database_cleaner.rb | |
RSpec.configure do |config| | |
# We don't use Rails' transactional tests because we use DatabaseCleaner instead. | |
# http://weilu.github.io/blog/2012/11/10/conditionally-switching-off-transactional-fixtures/ | |
config.use_transactional_tests = false | |
TABLES_NOT_TO_TRUNCATE = %w[ | |
schema_migrations | |
ar_internal_metadata | |
] | |
config.before(:suite) do | |
DatabaseCleaner.clean_with :truncation, except: TABLES_NOT_TO_TRUNCATE | |
Rails.application.load_seed | |
end | |
def require_transaction_for(example) | |
example.metadata[:requires_transaction] || | |
example.metadata[:js] | |
end | |
config.before(:each) do |example| | |
DatabaseCleaner.strategy = if require_transaction_for(example) | |
[:truncation, { except: TABLES_NOT_TO_TRUNCATE }] | |
else | |
:transaction | |
end | |
DatabaseCleaner.start | |
end | |
config.after do |example| | |
DatabaseCleaner.clean | |
Rails.application.load_seed if require_transaction_for(example) | |
end | |
end |
This file contains hidden or 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
# An example group that needs the transaction to be closed in order to pass. | |
context "DELETE destroy", :requires_transaction do | |
let(:the_request) { delete "/admin/sites/#{site.id}" } | |
let!(:site) { FactoryGirl.create(:site) } | |
it "deletes the site" do | |
the_request | |
expect { site.reload }.to raise_error(ActiveRecord::RecordNotFound) | |
end | |
end |
This file contains hidden or 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
# This example assumes that you have the following line uncommented in your spec_helper: | |
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment