Ruby Stub Variations:
IntroductionRuby Stub Variations:
OpenStructRuby Stub Variations:
TestStubRuby Stub Variations:
StructRuby 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.