ck3g
ck3g

Reputation: 5929

Stub associations

I have method and spec.

class Event
  def self.renew_subscription(user)
    subscription = user.subscription

    result = subscription.renew

    user.pay(subscription.plan.price_in_cents) if result

    result
  end
end


let!(:user) { create :user }

describe ".renew_subscription" do
  before do
    user.subscription.stub!(:renew).and_return(true)
    user.subscription.stub!(:plan).
      and_return(Struct.new("SP", :price_in_cents).new(699))
  end

  context "when have to pay" do
    it "pays" do
      user.should_receive(:pay)
      Event.renew_subscription user
    end
  end
end

There user belongs_to :subscription and subsription belongs_to :plan

Is there the way to stub subscription.renew and subscription.plan (or subscription.plan.price_in_cents)?

Upvotes: 1

Views: 506

Answers (1)

Geoff
Geoff

Reputation: 2228

I think it's probably safe for you to do something like this:

Subscription.any_instance.stub(:renew).and_return(true)
plan = mock_model(Plan)
Subscription.any_instance.stub(:plan).and_return(plan)
plan.stub(:price_in_cents).and_return(699)

There are probably other ways of doing it too, but I hope that helps.

Upvotes: 1

Related Questions