MarkUs Blog

MarkUs Developers Blog About Their Project

Understand unit test with gem ‘shoulda’

without comments

It was my first time to learn about unit test and the ‘shoulda’ gem in my recent ticket. I found it hard to learn it from scratch without any context. So I wrote this very simple introduction on unit test (specifically, with ‘shoulda’ gem) to provide you with a point where you can start to learn.

‘Shoulda’ is a meta gem that makes testing code looks simple and clear. Instead of writing ruby method with a lot of underscores, testers can use ‘context’ and ‘should’ keywords provided by ‘shoulda’.

One obvious advantage is that it makes test code reads more like natural language: to describe a specific test, first you need to mention the context, and then you must claim in this context, what behavior should appear to pass the test.

I will use the code in grouping_test.rb for example:


require 'shoulda'

context "A grouping" do
  setup do   
    @grouping = Grouping.make
  end
  
  should "not have any ta for marking" do
    assert !@grouping.has_ta_for_marking?
  end
  
  should "not have submissions" do
    assert !@grouping.has_submission?
  end
end

The keyword “context” is to describe the context of the test. Its following string do not have effect on the test result, only to make the test clear to read. The “setup” keyword is to setup any preparation work before each “should”. The code in “setup” will be executed every time before it run into another “should” test case. Similarly, we also have a “teardown” keyword to do cleanup after each “should” test case.

The string following the keyword “should” is the test case title. A good test case title should be clear and specific because it will appear in the output message if this test case fails.

Moreover, “context” can be nested to setup complicated situation while keeping the code clear. We can demonstrate this by adding a inner test case to the previous example:



require 'shoulda'

context "A grouping" do
  setup do
    @grouping = Grouping.make
  end

  should "not have any ta for marking" do
    assert !@grouping.has_ta_for_marking?
  end

  should "not have submissions" do
    assert !@grouping.has_submission?
  end

  context "and two unassigned tas" do
    setup do
      @ta1 = Ta.make
    end

    should "be able to add ta" do
      @grouping.add_tas(@ta1)
    end
  end
end

In the test case of “be able to add ta”, setup of both outer context and inner context will be executed in order before the test starts.

For more information about ‘Shoulda’, please take a look at:

A blog post from a previous MarkUs developer

A video tutorial about Shoulda on rails

Github page of Shoulda source code and document

Written by Sky

April 2nd, 2012 at 12:18 am

Posted in Uncategorized

Leave a Reply