ruby on rails - Testing association methods with Mocha -
i have rails app order , refund model. order has_many :refunds. , good. i'm trying write functional test refund logic in controller. here's have right now:
test "should not process partial paypal refund partially refunded order when refund total plus refund amount greater order total" set_super_admin_login_credentials o = order.new o.stubs({:id => 1234567, :source => "paypal", :total => 39.95, :user => users(:dave)}) order.stubs(:find).with(1234567).returns(o) :refund, {:order_id => 1234567} assert_equal o, assigns(:order) o.refunds.build.stubs({:amount => 1.0}) o.refunds.build.stubs({:amount => 30.00}) assert_raise post :refund, {:order_id => 1234567, :refund_amount => 10.00} end end
and in controller, refund method looks this:
def refund @order = order.find(params[:order_id]) return if request.get? amount = params[:refund_amount].to_f raise "cannot refund order more total" if (@order.refunds.sum(&:amount) + amount) # refund stuff end
some notes:
i'm basing
o.refunds.build
bit on ryan bates' railscast. if not right or no longer relevant, that's helpful information.i've seen lot of conflicting information how
sum
method,&
, without. inscript/console
,&
blows without it, actual sum. in controller, however, if switch&:amount
:amount
, message:nomethoderror: undefined method
+' :amount:symbol`
i feel there's conceptual information missing rather bug somewhere, i'll appreciate pointers.
finally figured out issue. stubbing empty association []
rather leaving nil
rails handle on other methods. so, when change one, other fail. word wise: enumerable#sum
, activerecord::associations::associationcollection#sum
take entirely different parameters. :)
so, changing stubs leave off :refunds => []
, using string field name in sum
got things normal. so, here's functional version of above code:
test "should not process partial paypal refund partially refunded order when refund total plus refund amount greater order total" set_super_admin_login_credentials o = order.new o.stubs({:id => 1234567, :source => "paypal", :total => 39.95, :user => users(:dave)}) order.stubs(:find).with(1234567).returns(o) :refund, {:order_id => 1234567} assert_equal o, assigns(:order) o.refunds.build.stubs({:amount => 1.0}) o.refunds.build.stubs({:amount => 30.00}) assert_raise post :refund, {:order_id => 1234567, :refund_amount => 10.00} end end def refund @order = order.find(params[:order_id]) return if request.get? amount = params[:refund_amount].to_f raise "cannot refund order more total" if (@order.refunds.sum('amount') + amount) # refund stuff end
Comments
Post a Comment