On Friday, April 27, 2012 at 3:54 AM, Christophe Porteneuve wrote:
> This is on a legacy project: Rails 2.3.14, rspec 1.3.2, rspec-rails 1.3.4 :-/
> 
> I've got a before(:each) setting up AR instances, so that I end up
> with a @product assign.
> 
> Then within a context, one of my "it" descriptions goes:
> 
> money = Money.new(5_00, 'EUR')
> fd = double('FlashSaleDiscount', :sale_total_cents =>
> money.cents)
> Rails.logger.debug '1>' * 70
> 
> @product.should_receive(:active_flash_sale_discount).and_return(fd)
> @product.min_money(:force).should == money
> Rails.logger.debug '<1' * 70
> 
> But when I run this, @product's *actual* active_flash_sale_discount
> method is called, not the stubbed version used by the should_receive
> expectation.
> 
> 

There is a guideline that you should not stub or set message expectations on 
the object you're testing. Doing so changes the runtime structure of the object 
in a way that never happens in the running system so it's quite possible to end 
up with false results. Not saying this is the source of your issue. Just saying 
:)

Usually when you set an expectation on an ActiveRecord model and the real 
message gets called it's because there is a finder involved that is building a 
new instance of the same data e.g.

  describe Thing do
    before do
      @thing_helper = ThingHelper.create!
      @thing = Thing.create!(:thing_helper_id => @thing_helper.id)
    end

    it "delegates to the helper" do
      @helper.should_receive(:help_me)
      @thing.do_something_that_needs_help
    end
  end

  class Thing < ActiveRecord::Base
    belongs_to :thing_helper
    def do_something_that_needs_help
      thing_helper.help_me
    end
  end

Here the do_something_that_needs_help loads a new copy of the ThingHelper with 
the same data as the @thing_helper set up in the before block, and sends 
`help_me` to that object instead.

I'd need to see the code the in the before(:each) block to be sure, but that is 
one place to look.
> Another thing that confuses me is that the before(:each) AR-creating
> code is, according to logs, triggered *after* the first
> Rails.logger.debug call. Is there some lazy evaluation stuff I'm not
> aware of in there? As for the final call, it doesn't show up in my
> logs since the should fails.
> 
> This test code used to work. I have no idea why it suddenly went dead.
> I thought this might be due to my running it through spork and guard,
> but reverting back to a bare-bones "spec spec/models/product_spec.rb"
> CLI had the exact same results.
> 
> 

Did anything change since the code did work? Diff version of Ruby? Upgraded any 
gems? Etc, etc.

David

-- 
You received this message because you are subscribed to the Google Groups 
"rspec" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rspec?hl=en.

Reply via email to