这是我的测试:
describe Item do
subject {Item.new(:report_id => 26 , :name => 'Gas' , :tax_rate => 0.13, :tax_id => 1 , :category_id => 15 , :sub_category_id => 31 , :job_id => 1 , :total => 20 )}
let(:tax) {Tax.where(id: subject.tax_id).first}
let(:sub_category) {SubCategory.where(id: subject.sub_category_id).first}
it 'Calculate with just Total' do
subject.name.should be == 'Gas'
tax = Tax.find_by_id(subject.tax_id)
subject.sub_category_id.should be == 31
subject.set_nil_values
sub_category.should_receive(:taxable).and_return(1)
tax.should_receive(:rate).and_return(0.13)
sub_category.should_receive(:tax_adjustment).and_return(nil)
subject.should_receive(:tax_rate).and_return(0.13)
subject.calculate_tax(tax, sub_category)
subject.tax_amount = (((subject.total - subject.deduction) - ((subject.total - subject.deduction) / (1 + 0.13))) * 1)
subject.calculate_cost
subject.cost.should be_within(0.01).of(17.70)
end
这是我的错误:
1) Item Calculate with just Total
Failure/Error: subject.should_receive(:tax_rate).and_return(0.13)
(#<Item:0x007faab7299c30>).tax_rate(any args)
expected: 1 time with any arguments
received: 3 times with any arguments
# ./spec/models/item_spec.rb:25:in `block (2 levels) in <top (required)>'
我做了一些研究,并尝试使用它:
expect_any_instance_of(subject).to receive(:tax_rate)
但现在出现以下错误:
1) Item Calculate with just Total
Failure/Error: expect_any_instance_of(subject).to receive(:tax_rate)
NoMethodError:
undefined method `method_defined?' for #<Item:0x007fe6fdaa1bf8>
# ./spec/models/item_spec.rb:25:in `block (2 levels) in <top (required)>'
答案 0 :(得分:1)
发生了初始错误,因为正如错误消息所述,所讨论的方法被调用了三次而不是一次,这是隐含的期望。假设实际行为是应该的,您可以将期望更改为:
...receive(...).exactly(3).times
有关详细信息,请参阅http://rubydoc.info/gems/rspec-mocks/frames。
对于您遇到的第二个错误,根据我的测试,当您将expect_any_instance_of
与已经存在实例存根的类一起使用然后调用该存根实例时,会发生这种情况。无论如何,即使这有效,我也不相信这是你想要的,因为expect_any_instance_of
的频率与expect
的语义相同,即“一个(总数) )调用存根实例“。
如果发生第二次错误而您没有删除subject
上的现有期望,请与我们联系。