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:
- ActiveRecord object is defined as follows:
class Ipv4Stats < ActiveRecord::Base
has_one :ipregistry
end - 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 })
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:
- The ActiveRecord object is defined as below:
class IpRegistry < ActiveRecord::Base
belongs_to :ipv4stats
end - The stub looks like:
IpRegistry.stub!(:find).and_return(0)
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