Created
October 15, 2008 03:49
-
-
Save Roman2K/16852 to your computer and use it in GitHub Desktop.
Test helper for painless record creation
This file contains 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
# Test helper for painless record creation. Details at: | |
# http://roman.flucti.com/painless-record-creation-with-activerecord | |
# | |
def insert!(model, attributes={}) | |
attributes = attributes.stringify_keys | |
begin | |
record = model.new(attributes) | |
def record.callback(*args) | |
# inhibit all callbacks | |
end | |
record.save(false) | |
rescue ActiveRecord::StatementInvalid | |
if $!.message =~ /Column '(.+?)' cannot be null/ | |
unless attributes.key?($1) | |
attributes[$1] = record.column_for_attribute($1).number? ? 0 : "" | |
retry | |
end | |
end | |
raise | |
end | |
return record | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment