我在测试以下模型时遇到问题:
class Bill < ActiveRecord::Base
belongs_to :consignee
before_save :calc_rate
def calc_rate
self.chargeableweight = self.consignee.destination.rate * self.weight
end
end
收货人模型:
class Consignee < ActiveRecord::Base
belongs_to :destination
has_many :bills
end
Controller 还没有被触及。
应用程序的行为是正确的(跟进问题:该解决方案是否存在任何性能问题?)- 但测试中断。
You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.*
谢谢你的建议, 丹尼
更新:
这个账单测试使用 factory girl 中断:
describe Bill do
it "should call the calc_rate method" do
bill = Factory.build(:bill)
bill.save!
bill.should_receive(:calc_rate)
end
end
当你没有预料到它时,你得到了一个 nil 对象!
工厂:
Factory.define :destination do |f|
f.airport_code "JFK"
end
Factory.define :consignee do |f|
...
f.association :destination
end
Factory.define :bill do |f|
f.association :consignee
f.weight 10
f.chargeableweight 20.0
f.after_create do |bill|
bill.calc_rate
end
最佳答案
describe Consignee do
it "should calculate the rate" do
#pending
#make sure this spec is passing first, so you know your calc_rate method is fine.
end
it "should accept calc_rate before save" do
cosignee = mock("Consignee")
consignee.should_receive(:calc_rate).and_return(2) # => stubbing your value
end
end
我没有假脱机运行 Rails 应用程序来测试这段代码,但这应该让你接近。此外,假设列 chargeable_rate、weight 等是模型上的列,您不需要调用 self.如果没有可用的实例方法或该名称的变量,Ruby 将隐式期望 self 它将自动查找类方法。
关于ruby-on-rails - 如何测试一个 before_save 方法,包括与 rspec 的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3434105/