Rspec-rails mock_model helper for the RR test double framework
9 Jul
Rspec-rails is a rails plugin which brings the Rspec Ruby Behaviour Driven Development framework to rails along with some rails specific helpers. One of these hugely useful helper functions is:
mock_model(model_class, options_and_stubs = {})
This creates a mock object with the common methods stubbed out. It also allows you to specify other methods you want to stub.
You can use Rspec with a number of mocking frameworks (Rspec 1.1.5: mocha, flexmock & RR). Unfortunately the Rspec-rails mock_model helper is not compatible with the RR test double framework.
It throws this error message:
undefined method `to_sym' for {:count=>0}:Hash
as it uses a stub function:
:errors => stub("errors", :count => 0)
which does not match RR’s stub method.
I’ve written a patch which will allow mock_model to work with RR. Note: It’s still a work in progress but I am using it successfully in a number of projects.
You can get the latest code from GitHub:
git clone git://github.com/josephwilk/rspec-rr.git
Spec::Rails::Mocks.module_eval do# Creates a mock object instance for a +model_class+ with common# methods stubbed out. Additional methods may be easily stubbed (via# add_stubs) if +stubs+ is passed.def mock_model(model_class, options_and_stubs = {})m = model_class.newid = next_id# our equivalent to Rspecs :errors => ''# stub("errors", :count => 0)stub(errors_stub = Object.new).count{0}options_and_stubs.reverse_merge!({:id => id,:to_param => "#{id}",:new_record? => false,:errors => errors_stub})options_and_stubs.each do |method,value|eval "stub(m).#{method}{value}"endyield m if block_given?mendend