【发布时间】:2014-03-31 06:49:46
【问题描述】:
我正在开发一个 Ruby on Rails 应用程序,我有一个包含以下方法的 BillingPlan 模型:
class BillingPlan < ActiveRecord::Base
# ...
def billing_months
dates = [Date.new(Date.today.year, start_month.value, billing_day)]
while dates.size < billings_in_year
dates << dates.last + recurrence.value.months
end
dates.map{ |d| d.month }
end
def billings_in_year
12 / recurrence.value
end
end
为了测试代码,我编写了以下规范:
describe BillingPlan do
# ...
describe '#billings_in_year' do
subject do
(plan = BillingPlan.new).stubs(
recurrence: stub(value: 4)
) && plan
end
it 'returns the number of billings in a year' do
expect(subject.billings_in_year).to eq(3)
end
end
describe '#billing_months' do
subject do
(plan = BillingPlan.new).stubs(
recurrence: stub(value: 2),
start_month: stub(value: 2),
billings_in_year: 6,
billing_day: 21
) && plan
end
it 'returns the months when billing is done' do
expect(subject.billing_months).to eq([2, 4, 6, 8, 10, 12])
end
end
end
如您所见,我已经设法通过使用 Mocha 完全隔离了这两种方法。但是,我想知道我是否在测试中滥用存根?是不是太依赖于方法的内部运作?您能否提供一个通用规则来了解一个人应该在多大程度上依赖模拟/伪造?
注意:recurrence 和 start_month 是第三方类的对象。
【问题讨论】:
标签: ruby unit-testing tdd stubbing