Skip to content

Instantly share code, notes, and snippets.

@sweatpantsninja
Created August 21, 2012 22:33

Revisions

  1. sweatpantsninja created this gist Aug 21, 2012.
    12 changes: 12 additions & 0 deletions user.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    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

    27 changes: 27 additions & 0 deletions user_spec.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    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