Tuesday, March 10, 2009

using multiple contexts block in test case with shoulda

Test::Unit which is a default unit testing framework with rails. It has only one context for each test case class. If we can have more than one context per class than it could reduce number of files and classes that we are required to make to test cases in multiple contexts.


Answer to this issue is support for multiple contexts in Shoulda. Shoulda is rspec like testing framework built upon Test::Unit. Shoulda allows you to have multiple context with thier own setup and teardown methods. For example see this context block in a test case




class UserTest < Test::Unit::TestCase
context "with user" do
setup do
@user = User.create(:login => "john", :password => "secret" )
end

should "be able to authenticate" do
assert User.authenticate("john", "secret")
end

should "return authenticated user" do
assert_equal @user, User.authenticate("john", "secret")
end
end
end


For more details on shoulda testing framework take a look at official rails wiki page