0

我有方法和规格。

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

有用户belongs_to :subscription和订阅belongs_to :plan

有没有办法存根subscription.renewsubscription.plan(或subscription.plan.price_in_cents)?

4

1 回答 1

1

我认为你这样做可能是安全的:

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)

可能还有其他方法可以做到这一点,但我希望这会有所帮助。

于 2013-01-03T23:53:27.060 回答