测试委托给另一个对象的方法

时间:2017-10-09 12:31:08

标签: ruby-on-rails ruby unit-testing rspec

这是我项目中的模型 -

class Subscription < ActiveRecord::Base
  def active?
    SubscriptionValidationPolicy.new(self).active?
  end
end

当我进行单元测试active?时,我应该为活动和非活动状态设置subscription并对其进行断言,或者我应该为SubscriptionValidationPolicy制作一个双精度,以某种方式注入它然后断言是否在其上调用了active?

或者只是看看我是如何进行测试的。无论如何,我将要测试SubscriptionValidationPolicy,因此对Subscription#active?方法进行“基于状态”测试感觉多余。

会喜欢这个想法:)

1 个答案:

答案 0 :(得分:3)

我同意@spickermann我会按如下方式设置测试:

#spec/models/subscription_spec.rb
#
describe Subscription do 

  let(:subscription) { Subscription.new }
  context '#active? delegation' do 
    let(:policy) {spy('subscription_validation_policy')}
    before :each do 
      allow(SubscriptionValidationPolicy).to receive(:new).and_return(policy)
      subscription.active?
    end

    it 'instantiates a SubscriptionValidationPolicy with self' do 
      expect(SubscriptionValidationPolicy).to have_received(:new).with(subscription)
    end
    it 'calls SubscriptionValidationPolicy#active?' do 
      expect(policy).to have_received(:active?)
    end
  end
end

然后实际测试SubscriptionValidationPolicy#active?以获取SubscriptionValidationPolicy规范中的逻辑注意事项。