简体   繁体   English

如何测试控制器中的RSpec关联已设置?

[英]How do I test RSpec association in controller was set?

I have the following: 我有以下几点:

let(:coupon) { mock_model Coupon, code: 'special' }
let(:cart) { mock_model Cart }

it "assigns a coupon to the cart" do
  post :redeem_coupon, coupon: {coupon: coupon.code}
  assigns(:cart).coupon.should eql(coupon)
end

I have the following error with that: 我有以下错误:

 Failure/Error: assigns(:cart).coupon.should eql(coupon)
 NoMethodError:
   undefined method `coupon' for nil:NilClass

I just want to make sure the following works: 我只想确保以下工作有效:

@cart = current_cart

if request.post?
  coupon = Coupon.find_active_by_code(params[:coupon][:coupon], @cart.subtotal, current_member)
  if coupon
    @cart.coupon = coupon
    @cart.save!
  end
end

I would guess current_cart is returning nil. 我猜想current_cart返回nil。 You can stub it with the mock cart that you already created: 您可以使用已经创建的模拟购物车将其存根:

before { subject.stub(:current_cart) { cart } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM