views:

33

answers:

2

Hi I have a user model with a lot of attributes and validation that I require to go in. I want to develop my application using test-driven development but am having a hard time writing simple tests for validations such as no blank emails, unique emails, proper email address.

So what's the best way to start writing tests?

A: 

Create a hash of valid attributes that will successfully create an object of the type you wish to test. This is typically done once in a before step. Then, for each attribute you want to check validations on create a test sort of like this (using rSpec syntax):

obj_under_test = MyModel.new(@valid_attributes)
object_under_test.email = nil
obj_under_test.should_not be_valid

In this case @valid_attributes is a hash you create. An alternative to this is to use sensible factories to generate your objects for each test. Look at FactoryGirl, Machinist, Fixjour for some examples. So using your example, something like this makes sense:

You can drive your tests/specs out to the level of granularity you like. Many people like to test only one thing per case (or "example", in BDD parlance). So you may have a forest of tests like "should have an email supplied", "should have a valid email if one is supplied", "should have an email at a valid domain", etc.

Steve Ross
+1  A: 

Shoulda ( http://github.com/thoughtbot/shoulda/wiki/Usage ) will allow checking of such ActiveRecord checks easily.

  should_not_allow_values_for :email, "blah", "b lah" 
  should_allow_values_for :email, "[email protected]", "[email protected]" 

Its reasonably clear what the code does and it includes a fair few useful checks like these.

David Lyod