Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Support unit testing AR models without loading all of rails
require "active_record"
# Also highly recommended:
# require "active_support/dependencies"
# ActiveSupport::Dependencies.autoload_paths += [ "app/models" ]
# ..so you don't need to do manual requires, found it to be just as fast.
# Support unit testing AR models without loading all of rails.
connection_info = YAML.load(ERB.new(File.read("config/database.yml")).result)["test"]
ActiveRecord::Base.establish_connection(connection_info)
# For errors_on in tests
require 'rspec/rails/extensions/active_record/base'
# Disable write queries
module ActiveRecord
UNIT_MESSAGE = "Persistance disabled in unit specs, if you want to test persistance put the example in spec (we want to keep unit tests fast)."
class Base
def readonly?
true
end
end
class ReadOnlyRecord
def message
UNIT_MESSAGE
end
end
end
# Disable read queries
connection = ActiveRecord::Base.connection
def connection.select_all(*)
raise ActiveRecord::UNIT_MESSAGE
end
def connection.select_value(*)
raise ActiveRecord::UNIT_MESSAGE
end
# Making uniqueness validations no-ops
class ActiveRecord::Validations::UniquenessValidator
def validate_each(record, attribute, value)
# no-op
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment