Testing your Ruby/Rails 3.x Model with Cucumber

So I’m working on a Ruby/Rails development project for a customer, and using TDD/BDD from word “Go”.  The weapon of choice here is Cucumber.  I know some of the more serious code-cutters prefer RSPEC, but I just like the “feel” of Cucumber.

Naturally, part of the job includes ensuring that the various Models in the project pass very basic tests, such as if they are defined properly.  In RSPEC, you can use a solid set of tools to do that, but Cucumber is much more “View” centric in the MVC than it is good for peeking at the Models.

So, for amusement, I decided I’d work out a simple Feature and Step set that can be used to verify a project Model.

The Cucumber Feature Code looks like:

File::UserModel.Feature:
Scenario: We are defining our User Model
Given we have a "User" Model
When we test the "User" Model
Then the Test Model should have attribute "first_name"
And the Test Model should have attribute "last_name"
And the Test Model should have attribute "email"

The Cucumber Step Code looks like:

File::project.steps.rb:
Given /^we have a "(.*?)" Model$/ do |model_name|
 eval("defined?(#{model_name}) && #{model_name}.is_a?(Class)") 
end
When /^we test the "(.*?)" Model$/ do |model_name|
 @test_model = Object.const_get(model_name).new
end
Then /^the Test Model should have attribute "(.*?)"$/ do |attribute|
 @test_model.has_attribute?(attribute).should == true
end

The “Given” simply tests to see if we have the Model name defined and if the defined Object is actually a Class instead of something else.

The “When” tries to actually create and instance of the Class.  Failure to do so stops the whole test right there.

Lastly, the “Then/And” section interrogates the Instance to verify that it actually has the attribute.  A similar code section could test a “have method” condition as well.

It’s fairly tight and elegant, and allows full unit tests from the Model design point upwards.  Let me know what you think.

Leave a Reply

Your email address will not be published. Required fields are marked *

Connect with Facebook

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>