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

  1. Spec::Rails::Mocks.module_eval do
  2.  
  3. # Creates a mock object instance for a +model_class+ with common
  4. # methods stubbed out. Additional methods may be easily stubbed (via
  5. # add_stubs) if +stubs+ is passed.
  6. def mock_model(model_class, options_and_stubs = {})
  7. m = model_class.new
  8. id = next_id
  9.  
  10. # our equivalent to Rspecs :errors => ''# stub("errors", :count => 0)
  11. stub(errors_stub = Object.new).count{0}
  12.  
  13. options_and_stubs.reverse_merge!({
  14. :id => id,
  15. :to_param => "#{id}",
  16. :new_record? => false,
  17. :errors => errors_stub
  18. })
  19.  
  20. options_and_stubs.each do |method,value|
  21. eval "stub(m).#{method}{value}"
  22. end
  23.  
  24. yield m if block_given?
  25. m
  26. end
  27.  
  28. end
blog comments powered by Disqus