Valid Model Parameters

written by Cyx on April 22nd, 2007 @ 09:55 AM

While writing tests in rails, we frequently use the pattern :

@article = create_article(:title => nil) @article.should have_at_least(1).error_on(:title)

and in the bottom of the test, we define a create_article. For the next model, say Project, you define also another one in the bottom.

Previously at our company, we’ve been extracting most of our valid model parameters into a module like so

module ValidParameters def valid_article { :title => 'My Article' } end end

Which is very useful when you need to create a model, and the last thing we want is unnecessarily having DAMP code.

But what of combining the two approaches?

I just created a module, which I’ll extract to a plugin at a future date which does exactly that. Basically you add parameters with a DSL-like syntax :

module ValidParameters valid :article, :title => 'My Article' valid :project, :name => 'Hedgehog', :owner_id => 1 end

and in your tests you can then do either :

post :create, :article => valid_article

or

lamba { create_article }.should have_difference(Article, :count)

or finally with invalid parameters

lambda { create_article(:title => nil) }.should_not have_difference(Article, :count)

Neat huh?

Post a comment