Topic: rspec and with_scope

Hello,

I'm trying to spec a method that scopes an AR model multiple times to (in the end) find only those records that match all those criteria.
I've seen people using a conditions array that in the end gets applied like:

x_atleast = 3
allowed_y = 5..9
wanted_z = 10
conditions = []
conditions << "x > #{x_atleast}"
conditions << "y between #{allowed_y.first} and #{allowed_y}.last"
conditions << "z = #{wanted_z}"
MyModel.find(:all, :conditions => conditions.join(' AND '))

While this works, the way I do this is (I think) more flexible, since AR is pretty smart with conditions.
If for example we want z to be nil, the above code would render incorrect SQL (z = '' instead of z IS NULL)
Also when allowed_y is passed as just a single number (instead of a range), the code would fail.

The way I do this is like this:

x_atleast = 3
allowed_y = 5..9
wanted_z = 10
MyModel.with_scope :find => { :conditions => ['x > ?', x_atleast] } do
  MyModel.with_scope :find => { :conditions => { :y => allowed_y }} do
    MyModel.with_scope :find => { :conditions => { :z => wanted_z }} do
      MyModel.find(:all)
    end
  end
end

If I don't want to scope a condition under some circumstances I do it like this
find_options = {}
find_options.merge! :conditions => { :z => wanted_z } unless wanted_z.nil?
MyModel.with_scope(:find => find_options) do
# rest

Anyway, I don't know if this realy is the best way, but that's not the point here.
My point is about speccing this stuff.

What I would want is a way to determine the final applied finder-conditions.
I could then spec out a few examples covering all possible options that can be applied.

In case there is no such thing, I think I would need to mock MyModel and use .should_receive(:with_scope).with ......
I already tried this, but since with scope gets called multiple times (within its own block), I couldn't find a way to test for what options get passed at what time. It seems using MyModel.should_receive(:with_scope) twice with different parameters does not work.

Any help?

tnx