这是我的测试:
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)>'
最佳答案
您最初的错误发生是因为,如错误消息所述,所讨论的方法被调用了三次而不是一次,这是隐含的期望。假设实际行为是应该的,您可以将期望更改为:
...receive(...).exactly(3).times
参见 http://rubydoc.info/gems/rspec-mocks/frames了解更多信息。
至于您遇到的第二个错误,根据我的测试,当您将 expect_any_instance_of
与一个已经 stub 实例的类一起使用,然后调用该 stub 实例时,就会发生这种情况。无论如何,即使这行得通,我也不相信这是您想要的,因为 expect_any_instance_of
的频率语义与 expect
相同,即“跨 stub 实例的一个(总)调用”。
如果第二个错误发生时您没有删除对 subject
的现有期望,请告诉我。
关于ruby-on-rails - RSPEC - 预期错误与接收错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20182361/