Pre 0.8.0 Validation Checker for RSpec
Nothing special, just a simple helper I threw together in a few minutes. It is used in model tests to verify that a column is required. A few usages follow.
def should_require_attribute(model, attrib_name, error_messages=[], invalid_value=nil)
# Collect the valid value
valid_value = model.send(attrib_name)
error_messages = error_messages.to_a.sort
# Set it to nil
model.send("#{attrib_name.to_s}=", invalid_value)
model.should_not_be_valid
model.should_have(error_messages.size).errors
model.errors.on(attrib_name).to_a.sort.should == error_messages
# Put things back where you found them
model.send("#{attrib_name.to_s}=", valid_value)
model.should_be_valid
end
# Simple case
specify "should be invalid without state" do
should_require_attribute(your_model, :state, "is required")
end
# More than one error expected
specify "should require a valid email address" do
should_require_attribute(your_model, :email_address, ["is required", "should be a valid format"])
end
# Invalid value other than nil
specify "should require a non .gov email address" do
should_require_attribute(your_model, :email_address, "can't contain .gov domains", "bigbrother@government.gov")
end