Thursday, September 21, 2006

Ruby Stub Variations: Stubba

Ruby Stub Variations: Introduction
Ruby Stub Variations: OpenStruct
Ruby Stub Variations: TestStub
Ruby Stub Variations: Struct
Ruby Stub Variations: Stubba

In my last entry I described how, using Struct, you can create stubs without creating your own stub implementations. Struct also provides you the power of creating and keeping reference to a class. But, on many occasions you don't need the extra capability. On these occasions the unnecessary flexibility requires you to enter additional code. There is another alternative that allows you to initialize a class similarly to OpenStruct: Stubba.

Stubba is a stubbing framework that provides great flexibility. The example test can be implemented using Stubba with the following code.
def test_values_are_appened_to_insert_statement
statement = Insert.into[:table_name].values do
stub(:to_sql=>'select column1, column2 from table2')
end
assert_equal "insert into table_name select column1, column2 from table2", statement.to_sql
end
Stubba provides the same simplicity of OpenStruct and addresses the limitations. Stubba correctly responds to predefined methods and even returns as expected from respond_to?. However, the major benefit to using Stubba is the ability to temporarily change behavior of existing objects. For example, if I chose to use the Select class, but wanted to stub out the to_sql method I would use the following code.
def test_values_are_appened_to_insert_statement
Select.any_instance.stubs(:to_sql).returns('select column1, column2 from table2')
statement = Insert.into[:table_name].values do
Select[:column1, :column2].from[:table2]
end
assert_equal "insert into table_name select column1, column2 from table2", statement.to_sql
end
Stubba is a great alternative to the previously mentioned stub alternatives. In the end, which stub you choose should be based on your needs of your project.

1 comment:

  1. Anonymous7:41 PM

    Hi Jay

    I've been following your stubbing series - glad to see Stubba get mentioned at last. It really is a bit of a hidden gem right now; more people need to be aware of it.

    There is one downside with Stubba right now for BDD/RSpec fans...as of the latest versions of each, Stubba has a test::unit dependency that causes problems with RSpec. I hope to speak to the guys behind Stubba and see if we can get this fixed, because I love RSpec and I really want to carry on using Stubba (as I have been doing with RSpec up until the breakage).

    ReplyDelete

Note: Only a member of this blog may post a comment.