Skip to content

Instantly share code, notes, and snippets.

@aaronjensen
Created November 15, 2012 19:32
Show Gist options
  • Select an option

  • Save aaronjensen/4080690 to your computer and use it in GitHub Desktop.

Select an option

Save aaronjensen/4080690 to your computer and use it in GitHub Desktop.
Prevent database access in specs
# place in spec/support/prevent_database_access.rb
ActiveRecord::ConnectionAdapters::Mysql2Adapter.class_eval do
def execute_with_prevent_database_access(sql, name=nil)
if prevent_database_access?(sql)
raise "You should only access the database in model and acceptance specs.
If you really need to you can use :db to grant access for that spec.
Offending query: \"#{sql}\""
end
execute_without_prevent_database_access(sql, name)
end
alias_method_chain :execute, :prevent_database_access
def prevent_database_access?(sql)
return false unless ActiveRecord::ConnectionAdapters::Mysql2Adapter.prevent_database_access
sql =~ /^(SELECT|UPDATE|INSERT|DELETE)/
end
class << self
attr_accessor :prevent_database_access
end
end
RSpec.configure do |config|
config.backtrace_clean_patterns << %r{#{__FILE__}}
config.before :each do
# Prevent database access unless :db is true or we're in a :request
# or :model spec. Customize to suit your needs.
ActiveRecord::ConnectionAdapters::Mysql2Adapter.prevent_database_access =
!(example.metadata[:db] || [:request, :model].include?(example.metadata[:type]))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment