The ramblings of Chad Humphries

Custom expectations in rspec (pre 0.8.0)

Nothing special, just a simple helper I threw together a while back. It is used in model tests to verify that a column is required. A few usages follow. Note: this will be completely replaced in rspec 0.8.0 by custom expectation matchers. But I’ve had this one around for a while in one form or another, so I figured I’d post it up in case it helps anyone.

The code

 1   def should_require_attribute(model, attrib_name, error_messages=[], invalidvalue=nil)
 2     # Collect the valid value
 3     valid_value = model.send(attrib_name)
 4     error_messages = error_messages.to_a.sort
 6     # Set it to nil
 7     model.send("#{attrib_name.to_s}=", invalid_value)
 9     model.should_not_be_valid
10     model.should_have(error_messages.size).errors
11     model.errors.on(attrib_name).to_a.sort.should == error_messages
13     # Put things back where you found them
14     model.send("#{attrib_name.to_s}=", valid_value)
15     model.should_be_valid
16   end


 1 # Simple case
 2 specify "should be invalid without state" do
 3    should_require_attribute(your_model, :state, "is required")   
 4 end
 6 # More than one error expected
 7 specify "should require a valid email address" do
 8    should_require_attribute(your_model, :email_address, ["is required", "should be a valid format"])   
 9 end
11 # Invalid value other than nil
12 specify "should require a non .gov email address" do
13    should_require_attribute(your_model, :email_address, "can't contain .gov domains", "bigbrother@government.gov")   
14 end

Written by spicycode

February 23, 2007 at 6:00 pm

Posted in programming

Tagged with , ,

%d bloggers like this: