Is there a way to verify if the following is true within the model?
validates_numericality_of :employee_id, :original_value, :new_value :only_integer
=> true
and they are less then 50 but >= 0?
validates_inclusion_of :original_value, new_value :in => 0..50
orig_value and new_value are either whole or half numbers eg 12.0 or 3.5
def validate
# do you custom validation here
end
# Set the value and it should fail since it is valid,
# but no failure appears when run!!
edits_time.employee_id = 123
assert edits_time.errors.invalid?(:employee_id)
I believe this is going to pass because you did not ask to validate
the object again, so you errors has not changed from the original
invalid state.
edits_time.employee_id = 123
assert edits_time.valid?
assert edits_time.errors.invalid?(:employee_id)
the last assertion here should fail because the errors has been
updated by the previous line.
in def validate, can I have multiple validates, ie one for the value
fields, and then a second validate function for say source_table? Would
it require separate validates ie def validate_value, def
validate_source_table
An example is worth a thousand words:
class Person < ActiveRecord::Base
protected
def validate
errors.add_on_empty %w( first_name last_name )
errors.add("phone_number", "has invalid format") unless
phone_number =~ /[0-9]*/
end
def validate_on_create # is only run the first time a new object
is saved
unless valid_discount?(membership_discount)
errors.add("membership_discount", "has expired")
end
end
def validate_on_update
errors.add_to_base("No changes have occurred") if
unchanged_attributes?
end
end
How do I call the validate within the model, or is it automatically run?
Rails will take care of calling validation at the appropriate time.
Second was about the failure of the failure. You said that I did not ask
to validate the object again. Could you explain that in more detail?
How do I force an object to be validated multiple times within a single
test? ie If I had a test to check all boundary conditions of 1
parameter I'd like it to evaluate it each time it is changed.
Sorry I should have been more clear. s.ross answered this tersely,
yet correctly.
edits_time.valid?
or
assert edits_time.valid? # if you want to test the changed state