1 module ValidationTestHelper
2 def assert_valid(field, *values)
4 values.flatten.each do |value|
5 o = __setup_model__(field, value)
9 messages = [o.errors[field]].flatten
10 assert_block("unexpected invalid field <#{o.class}##{field}>, value: <#{value.inspect}>, errors: <#{o.errors[field].inspect}>.") { false }
15 def assert_invalid(field, message, *values)
17 values.flatten.each do |value|
18 o = __setup_model__(field, value)
20 assert_block("field <#{o.class}##{field}> should be invalid for value <#{value.inspect}> with message <#{message.inspect}>") { false }
22 messages = [o.errors[field]].flatten
23 assert_block("field <#{o.class}##{field}> with value <#{value.inspect}> expected validation error <#{message.inspect}>, but got errors <#{messages.inspect}>") { messages.include?(message) }
29 raise "@model must be assigned in order to use validation assertions" if @model.nil?
32 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?
35 def __setup_model__(field, value)
37 attributes = o.instance_variable_get('@attributes')
38 o.instance_variable_set('@attributes', attributes.dup)
39 o.send("#{field}=", value)