[rspec-users] Mocking with Calculated Results

s.ross cwdinfo at gmail.com
Mon Apr 30 16:20:36 EDT 2007


I am setting up an AR mock object and wanted to sanity check it. My  
intent is to mix this into all my examples and then override/add  
methods where necessary. Note that I've anticipated three cases for  
find:

find with one numeric argument => object
find with :all => Array
find with anything else => nil

This roughly approximates how ActiveRecord::find works in this case  
(neglecting the optional parameters).

My question is: Is this calculation of the return value a bad thing,  
and if so, how better to accomplish it?

Thanks

---------

module SettingsMock
   def setup_mock
     @countable = mock('countable')
     @countable.stub!(:count).and_return(1)
     @countable.stub!(:full_messages).and_return(['a message'])
     @setting = mock_model Setting do |m|
       m.stub!(:save).and_return(true)
       m.stub!(:destroy)
       m.stub!(:errors).and_return(@countable)
       m.stub!(:setting_name).and_return('first_name')
       m.stub!(:setting_value).and_return('first_value')
       m.stub!(:setting_type).and_return('first_type')
     end
     Setting.should_receive(:find).any_number_of_times.and_return do |a|
       case a
         when :all then [@setting, @setting]
         when /\d+/ then @setting
         else
           nil
       end
     end
   end
end



More information about the rspec-users mailing list