RSpec - 在关联模型上调用的方法的NoMethodError

时间:2013-11-24 21:32:18

标签: ruby-on-rails testing rspec

我正在尝试测试我的费用报告应用。当我计算一个项目的税时,我需要查找是否应该对项目征税。

我的item_spec.rb:

describe Item do
  subject {Item.new(:report_id => 26 ,  :name => 'Gas' ,  :tax_id => 1 ,  :category_id => 15 ,  :sub_category_id => 1 ,  :job_id => 1 , :total => 20 )}
  let(:tax) {Tax.find_by_id(subject.tax_id)}
  let(:sub_category) {SubCategory.find_by_id(subject.sub_category_id)}

  it 'Calculate Taxes and Cost' do
    subject.set_nil_values    
    subject.calculate_tax(:tax, :sub_category)
  end
end

这是我得到的错误:

  1) Item Calculate with just Total
     Failure/Error: subject.calculate_tax(:tax, :sub_category)
     NoMethodError:
       undefined method `rate' for :tax:Symbol
     # ./app/models/item.rb:88:in `calculate_tax'
     # ./spec/models/item_spec.rb:21:in `block (2 levels) in <top (required)>'

这是我在“calculate_tax”方法中失败的行:

self.tax_rate = tax.rate

我需要做些什么来完成这项工作?

1 个答案:

答案 0 :(得分:1)

尝试直接调用传递calculate_taxtax助手的函数sub_category而不是符号,如下所示:

subject.calculate_tax(tax, sub_category)

请在此处查看文档和用法:Let and let!