ruby-on-rails - 如何测试一个 before_save 方法,包括与 rspec 的关联

标签 ruby-on-rails ruby unit-testing rspec

我在测试以下模型时遇到问题:

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/

相关文章:

ruby-on-rails - 当尝试使已捕获的平衡付款的保留无效时,为什么响应是 is_void == true 的保留?

ruby-on-rails - 如何检查字符串的最后一个字母?

html - 调试信息显示为页脚的一部分并且只显示一行? Michael Hartl 的 Ruby on Rails 教程第 7 章

unit-testing - Mocking : Unit test question 中的依赖项太多

c# - 从另一个方法内部调用的方法的单元测试返回值

ruby-on-rails - `allow_any_instance_of` 模拟不在范围内工作

ruby-on-rails - Rails:参数数量错误(给定2个,预期为1个)MongoID

ruby-on-rails - 如何为 Timeout::error 定义类范围的救援方法?

ruby - Sunspot Solr 自动完成功能无法在 Ruby on Rails 3.2.3 上运行

unit-testing - 如何断言从不使用 ScalaTest 和 ScalaMock 调用模拟方法?