niedziela, 26 grudnia 2010

Ruby: Mocks and stubs

Recently I was looking for a description on how to execute unit tests in Ruby with mocks and stubs and was not able to easily find a helpful answer. First of all I wanted to mock the access to the database (ActiveRecord) and stub methods for accessing/finding the data.

Mocks

Ruby provides support for mocking with the rspec:mocks module. Below I enclose an example how to mock access to the db for a simple activerecord object:
  1. ActiveRecord object is defined as follows:
    class Ipv4Stats < ActiveRecord::Base
    has_one :ipregistry
    end
  2. Mock the Ipv4Stats object in spec file as below:
    new = mock(:ipv4stats,
    { :registry_id => reg_id, :date1 => date1, :date2 => date2,
    :ipv4_sum => ipv4_sum, :prefix_ipv4 => ipv4_prefix })

The newly created new object will contain the mocked version of the Ipv4Stats.

Stubs

In the same module (rspec:mocks) Ruby provides means for stubbing. Below I enclose an example how to stub a find method - I still have not found a way to stub the find method with parameters:

  1. The ActiveRecord object is defined as below:
    class IpRegistry < ActiveRecord::Base
    belongs_to :ipv4stats
    end
  2. The stub looks like:
    IpRegistry.stub!(:find).and_return(0)
It is also possible to give more criteria for stubs like in the examples below:

1. Different return values based on the parameters:

@stub_handler.stub!(:getRegistryById).with(1).and_return(@rirs[0])
@stub_handler.stub!(:getRegistryById).with(2).and_return(@rirs[1])

2. Number of expected invocations with specific parameters:
drawer.should_receive(:insertChartDataForRegistry).with(g,0).exactly(registries.size).times

As soon as I make or get to the tests where the database find access based on the argument is required I will extend this article.

Brak komentarzy:

Prześlij komentarz