Rails应用程序正常工作,但不在rspec测试中。 “nilclass”

时间:2012-08-10 22:00:43

标签: ruby-on-rails ruby-on-rails-3 rspec

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

浏览器中的一切正常。但是在运行规范时,我得到了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

1 个答案:

答案 0 :(得分:1)

问题似乎是Option.find_by_name(name)正在返回nil。

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

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

相关问题