Wednesday, November 12, 2008

rspec macro methods in Merb

While working on spec'ing out this merb-service-example app I came to a point where I had a lot of repetitive code, enough that I really wanted to DRY it up a bit. Long story short, after talking with David Chelimsky for a bit, I ended up with this: gists_spec.rb

I think the it_should_respond_with and it_should_return methods work well for adding clarity, reducing repetition, and making the specs even stronger. Still, I'm a bit unhappy with the method names. Some other possibilities thrown out there are:



Nothing feels perfect yet...and maybe it doesn't need to be...but, that's never stopped me from trying. What name(s) do you like? Any better suggestions?

3 comments:

Anonymous said...

Hey Jack,

I totally like these helpers and I like the original names best! I vote for:

it_should_respond_with OK
it_should_return :json

cheers
snusnu

Unknown said...

At first I liked them. Now I am having second thoughts. It is kinda lost that those methods are stamping out examples.

I am still new to Rspec, but does it make sense to do this with a bit more sugar using a factory??

it.should :return => :json
it.should :respond_with => OK

kinda a short hand way to code an example after setting up a template for the :return example...

Could probably even chain with this kinda sugar:

it.should :respond_with => OK, :return => :json

don't know if this is the best idea, or if this syntax would be any better, but branching off of 'it' would make it clear that this is an example.

Nick

Jack Dempsey said...

snusnu,

thanks, i like those best as well out of the choices i listed...however, as nick pointed out, there could be another way of doing it.

nick,

It seems like there will be some updates to rspec (on edge currently) that allow for more terse declarations, close to what you came up with. The one part that I'm hesitant about is that return is vague, and respond_with only slightly less. In some ways it should almost be:

it_should_have_content_type :json
it_should_return_status_code OK

But then that feels unnecessarily long. I was also thinking about something like:

it_should_have do
content_type :json
status_code OK
...
end

We'll see where this goes. Thanks for the comments.