Created
August 29, 2008 08:24
-
-
Save josephwilk/7936 to your computer and use it in GitHub Desktop.
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
module ValidationTestHelper | |
def assert_valid(field, *values) | |
__model_check__ | |
values.flatten.each do |value| | |
o = __setup_model__(field, value) | |
if o.valid? | |
assert_block { true } | |
else | |
messages = [o.errors[field]].flatten | |
assert_block("unexpected invalid field <#{o.class}##{field}>, value: <#{value.inspect}>, errors: <#{o.errors[field].inspect}>.") { false } | |
end | |
end | |
end | |
def assert_invalid(field, message, *values) | |
__model_check__ | |
values.flatten.each do |value| | |
o = __setup_model__(field, value) | |
if o.valid? | |
assert_block("field <#{o.class}##{field}> should be invalid for value <#{value.inspect}> with message <#{message.inspect}>") { false } | |
else | |
messages = [o.errors[field]].flatten | |
assert_block("field <#{o.class}##{field}> with value <#{value.inspect}> expected validation error <#{message.inspect}>, but got errors <#{messages.inspect}>") { messages.include?(message) } | |
end | |
end | |
end | |
def __model_check__ | |
raise "@model must be assigned in order to use validation assertions" if @model.nil? | |
o = @model.dup | |
raise "@model must be valid before calling a validation assertion, instead @model contained the following errors #{o.errors.instance_variable_get('@errors').inspect}" unless o.valid? | |
end | |
def __setup_model__(field, value) | |
o = @model.clone | |
attributes = o.instance_variable_get('@attributes') | |
o.instance_variable_set('@attributes', attributes.dup) | |
o.send("#{field}=", value) | |
o | |
end | |
end |
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
it 'should validate length of' do | |
{ | |
:title => 255, | |
}.each do |field, max| | |
assert_invalid field, ('%d-character limit' % max), 'x' * (max + 1) | |
#TODO: this line cannot work - as it used clone and slug must be uniq | |
#assert_valid field, 'x' * max | |
end | |
end | |
it 'should validate presence of' do | |
[:title].each do |field| | |
assert_invalid field, 'required', "", nil | |
end | |
end | |
it 'should validate format of' do | |
assert_valid :slug, 'abc', 'abcd-efg', 'abcd_efg', 'abc.html', '/', '123' | |
assert_invalid :slug, 'invalid format', '!@£!@£$' | |
end | |
it 'should magic invalid slugs into valid ones' do | |
assert_valid :slug, 'abcd efg' ' abcd', 'abcd/efg', '£$ test @£@£' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment