views:

83

answers:

3

I think shoulda is really neat, but what I don't understand is why some of the macros exist, such as:

  • should_validate_uniqueness_of :title
  • should_validate_presence_of :body, :message => /wtf/
  • should_validate_presence_of :title
  • should_validate_numericality_of :user_id

I'm relatively new to testing, but what purpose do these serve? They're almost an exact mirror of the same validations that happen in the model. For example, what exactly do you accomplish by going into your model and writing validates_uniqueness_of :title and then writing a test that says should_validate_uniqueness_of :title?

+1  A: 

I haven't used shoulda, and I don't know exactly what the authors were thinking, but I've written many Ruby unit tests over the years, so I'll take a guess.

Some parts of a program can be declared in RoR purely declaratively, like validate_uniqueness_of. Other things you write more sophisticated methods to implement. A class will usually consist of a combination of both of these. Note that the latter will typically take a lot longer (in time and space) to write than the former.

So if one was interested in sketching out the design for a class, perhaps because one was excited about "TDD", one might write a test that declared everything the class needed to support: title is unique, user ID is a mersenne prime, whatever. This is quick and simple to write. Then one would go write code for all of this, knowing the class's contract, and being able to see it in concise form.

That's just a guess.

Ken
And then, when some moron removed title uniqueness and broke the contract, the test would fail, and you'd then know it is broken (or that the contract is broken, in which case any function which calls it might need to change).
Brian
A: 

Those are macros specific for RSpec & ActiveRecord.

Yep, Shoulda actually plays with RSpec.

http://robots.thoughtbot.com/post/159805987/speculating-with-shoulda

The Who
I'm not asking what they are, I'm asking what the point of them is..
ryeguy
+1  A: 

It's for people who want complete defensive test coverage, as in, if someone breaks any function of the app, a test will fail.

mckeed