这是我项目中的模型 -
class Subscription < ActiveRecord::Base
def active?
SubscriptionValidationPolicy.new(self).active?
end
end
当我进行单元测试active?
时,我应该为活动和非活动状态设置subscription
并对其进行断言,或者我应该为SubscriptionValidationPolicy
制作一个双精度,以某种方式注入它然后断言是否在其上调用了active?
?
或者只是看看我是如何进行测试的。无论如何,我将要测试SubscriptionValidationPolicy
,因此对Subscription#active?
方法进行“基于状态”测试感觉多余。
会喜欢这个想法:)
答案 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
规范中的逻辑注意事项。