0

创建合同时,它需要一个单位、用户和折扣,并使用这些参数项(模型)来生成发票。

在浏览器中一切正常。但是在运行规范时,我得到undefined method 'value' for nil:NilClass [/app/models/option.rb:19:in 'get_from_database'

Option.rb 的第 18-20 行。这是从数据库中获取站点选项(可由管理员配置)的模型。正常工作(浏览器测试)。

def self.get_from_database(name)
  $option[name] = self.find_by_name(name).send('value')
end

它是从 Contract.rb 调用的:

def start_date=(date)
    self[:start_date] = Date.strptime(date, Option.get_from_database('short_date'))
end

知道为什么我会收到此错误吗?如果我注释掉这一行并重新运行规范测试,我会nil:NilClass从另一个类方法调用中得到另一个错误。

我刚刚开始使用 rspec,所以我确定我错过了一些东西。注意:第一个测试有效,第二个无效。

require 'spec_helper'

module ContractSpecHelper
  def contract_params
    {  :start_date => "08/09/2012",
       :client_id => '1', 
       :pay_interval_id => '1', 
       :billing_day => "1",
       :prorated => '1',
       :require_next => "1",
       :include_today => "1",
       :unit_id => '45',
       :due => "1" }
  end
end

describe 'Contract' do
  include ContractSpecHelper

  before :each do
    @contract = Contract.new
  end

  describe '#new' do
    it "requires a unit, user, and pay interval id" do
      @contract.should_not be_valid
    end

    it "creates an invoice once saved" do
      @contract.attributes = contract_params
      @contract.save

      @contract.should have(1).invoice
    end
  end

end
4

1 回答 1

1

问题似乎Option.find_by_name(name)是返回零。

最可能的原因是您没有在测试环境中填充选项表。更改您的代码以处理不存在的选项记录,或在块(等)之前使用 fixtures/factory_girl/machinist/ 在您的测试环境中创建选项记录。

(要回答您的其他问题,您的环境应该加载到您的 spec_helper 中。您不需要手动将 Rails 模型包含到您的 rspec 规范中。)

于 2012-08-10T23:20:57.093 回答