Daniel Fischer
Daniel Fischer

Reputation: 3062

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

Upvotes: 0

Views: 326

Answers (1)

Steve
Steve

Reputation: 15736

I would guess current_cart is returning nil. You can stub it with the mock cart that you already created:

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

Upvotes: 1

Related Questions