Skip to content

Instantly share code, notes, and snippets.

@sweatpantsninja
Created August 21, 2012 22:33
Show Gist options
  • Save sweatpantsninja/3420028 to your computer and use it in GitHub Desktop.
Save sweatpantsninja/3420028 to your computer and use it in GitHub Desktop.
stubbing sum vs reduce
class User < ActiveRecord::Base
has_many :orders
has_many :order_items, :through => :orders
def revenue
#TODO: stubbing OrderItem#price means I can't use .sum(:price). Is there a better way to use stubs AND sql?
#order_items.kept.sum(:price)
order_items.kept.reduce(0) { |sum, n| sum + n.price }
end
end
require "spec_helper"
describe User do
before(:each) {
OrderItem.any_instance.stub(:price).and_return(25)
}
describe "#revenue" do
context "no orders" do
specify { user.revenue.should == 0 }
end
context "one order" do
specify { user_with_no_kept_items.revenue.should == 0 }
specify { user_with_all_kept_items.revenue.should == 125 }
specify { user_with_one_kept_item.revenue.should == 25 }
end
context "multiple orders" do
it "should return 50 for two orders, each with one kept item" do
2.times { FactoryGirl.create :order_with_one_kept_item, user: user }
user.revenue.should == 50
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment