views:

23

answers:

1

Let me preface this be saying that I'm newb to both TDD and Ruby on Rails.

I'm using Rspec to perform unit testing of my data layer and to ensure that my database is rejecting invalid input.

My rspec code looks as follows:

it "should fail at saving without name" do
  @my_data.attributes = valid_my_data_attributes.except(:name)
  @my_data.save_with_validation( false ).should be_false
end

My database (Postgres) is correctly rejecting the data, but rather than returning false, it is throwing an error. How would I correctly catch that error and pass the test?

Thanks!

+1  A: 

Supposing your model looks like this:

class Customer
  validates_presence_of :name, :other_attribute
end

In your spec, you can check that the model has errors on a specific attribute

it "should require name" do
  create_customer(:name => nil).should have(1).errors_on(:name)
end

it "should create a valid customer" do
  create_customer.should be_valid
end

# factory method
def create_customer(attributes = {})
   Customer.create({:name => 'foo', :other_attribute => 'foo'}.merge(attributes))
end
I actually ended up getting two errors using this, but it's because I have two constraints on :name, one for NOT NULL, and one for LENGTH > 0, so if I test with :name => "", I get one error for the length.
Bryan Marble