存根关联

时间:2012-12-07 19:24:03

标签: ruby-on-rails-3 rspec stub

我有方法和规范。

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)?

1 个答案:

答案 0 :(得分: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)

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