# check_model_attributes_when_nil(model, required_attributes, attributes_with_error_messages = []) # {{{
#
# Ensures that an instance of the specified model:
# -is valid when an optional attribute is nil,
# -is invalid when a required attribute is nil,
# -has an error message on certain attributes when those attributes are nil
#
# Arguments:
# -The 'model' argument must be a model class.
# -The 'required_attributes' argument must be an array.
# -The 'attributes_with_error_messages' argument is optional. If used, it must be an array.
#
# An exception is raised if an argument is invalid.
#
# Example call:
# # The 'hashed_password' and 'salt' attributes, when nil, should not have error messages because
# # instead of being specified by the application's user, they are generated by the modelinstead.
# # The 'password' attribute, when nil, should have an error message because it is specified by
# # the application's user, and needed for generating the hashed password.
# check_model_attributes_when_nil User, [username, password, hashed_password, salt], [username, password]
#
def check_model_attributes_when_nil(model, required_attributes, attributes_with_error_messages = [])
raise 'The 1st argument (model) must be a model class.' unless model.is_a? Class
raise 'The 2nd argument (required_attributes) must an array.' unless required_attributes.is_a? Array
raise 'The 3rd argument (attributes_with_error_messages) must be an array.' unless attributes_with_error_messages.is_a? Array
columns_to_check = model.column_names
columns_to_check.delete 'id'
columns_to_check.delete 'created_at'
columns_to_check.delete 'updated_at'
columns_to_check.each do |attribute|
describe model, "with '#{attribute}' set to nil" do
before(:each) do
@model_instance = Object.send "build_#{model.to_s.downcase}", {attribute => nil}
@model_instance.save
end
if required_attributes.include? attribute
it "should be invalid" do
@model_instance.should_not be_valid
end
else
it "should be valid" do
@model_instance.should be_valid
end
end
if attributes_with_error_messages.include? attribute
it "should have an error message for '#{attribute}'" do
@model_instance.errors[:"#{attribute}"].should_not be_nil
end
end # if
end # End describe
end # End .each
end # }}}