[rspec-users] Mocking with Calculated Results

David Chelimsky dchelimsky at gmail.com
Mon Apr 30 16:37:00 EDT 2007


On 4/30/07, s.ross <cwdinfo at gmail.com> wrote:
> 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,

Well, it will make failures more difficult to understand. In my book,
that is a very bad thing.

> and if so, how better to accomplish it?

How about parameterizing setup_mock or coming up w/ 3 separate methods
to create the mocks that are supposed to behave 3 different ways?

Cheers,
David

>
> 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
>
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>


More information about the rspec-users mailing list