Last active
August 29, 2015 13:55
-
-
Save joakimk/8703877 to your computer and use it in GitHub Desktop.
Support unit testing AR models without loading all of rails
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
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