[rspec-users] Spec'ing methods which essentially filter associations

deploy deyolped at gmail.com
Sat Oct 23 09:04:12 EDT 2010


I've been spec'ing for a long time, but I've never discovered the
answer to this, so a definitive answer would be great!

Whats the best way to spec a method which basically filters an
association?

class Thing < ActiveRecord::Base
  has_many :others

  def foos
    others.all(:conditions => { ... })
  end
end

I don't like the idea of creating a load of associated records in my
spec and testing the returned result as I am not testing the
associated model and as such would prefer any references to it to be
mocked out, so the best I can some up with is this super lame test
which is clearly way too implementation specific and essentially
useless.

describe Thing do
  describe 'foos' do
    before :each do
      @thing = Thing.new
      @others_proxy = mock('others proxy')
      @others_proxy.stub!(:all)
      @thing.stub!(:others).and_return(@others_proxy)
    end

    it 'should return the associated others which meet the conditions'
do
      @others_proxy.should_receive(:all).with({ :conditions => ' ...
' })
      @thing.foos
    end
  end
end

So what's the best practice in this case?

Pastie is here for pretty formatting: http://pastie.org/1242892

Thanks.

P.S. This is old code I've inherited so I'm just trying to retrofit
RSpec 1.3x to it before I start refactoring and bringing up to date
with rails 3/rspec 2, so basically what I mean is what's the answer if
the model simply is how it is and can't be changed?


More information about the rspec-users mailing list