ruby-on-rails 无方法错误:运行Rspec时nil:NilClass的方法'fetch_value'未定义

e3bfsja2  于 2023-03-20  发布在  Ruby
关注(0)|答案(1)|浏览(175)

我使用rspec ./spec/models/prediction_spec.rb运行这个rspec文件

require 'rails_helper'
require 'prediction.rb'

RSpec.describe Prediction, type: :model do
  context "validations tests" do
    it "ensures zip presence" do
      prediction = Prediction.new(zip: "zip").save
      expect(prediction).to eq(false)
    end

    it "ensures school presence" do
      prediction = Prediction.new(school: "school").save
      expect(prediction).to eq(false)
    end

    it "should save successfully" do
      prediction = Prediction.new(zip: "zip", school: "school").save
      expect(prediction).to eq(true)
    end
  end

  context "scope tests" do
    let(:params) { { zip: "zip", school: "school" } }
    before(:each) do
      Prediction.new(params).save
      Prediction.new(params).save
      Prediction.new(params).save
    end

    it "should return all predictions" do
      expect(Prediction.count).to eq(3)
    end
  end
end

下面是我的预测模型:

class Prediction < ApplicationRecord
    #belongs_to :user

    def getRequest
        response = HTTParty.get('https://sdp-api.herokuapp.com/api/v1/query/' + @prediction.zip)
        @inch = response["snow"]
        @temp = response["temp"]
    end

    def percentage
        #for our weighing purposes
        weight_1 = inch/5.0
        weight_2 = temp/32.0

        #standardize weights
        if weight_1 >= 1
            weight_1 = 0.7
        else
            weight_1 = weight_1 * 0.7
        end
        
        if weight_2 <= 1
            weight_2 = 0.3
        else
            weight_2 = 0
        end

        return 95 * (weight_1 + weight_2)
    end

    #getters and setterss
    # attr_accessor :inch
    # attr_accessor :temp
end

当我运行它时,在包含.保存的每一行上都得到以下错误:

NoMethodError:
       undefined method `fetch_value' for nil:NilClass

为什么会发生这种情况?其他类似的问题列出了有保留字的数据库列,而我的数据库没有保留字。另外,这似乎与这些错误所暗示的不太接近。

yk9xbfzb

yk9xbfzb1#

在一天结束的时候,我自己从来没有看到过这个错误。看起来ActiveRecord内部出现了可怕的错误。
一个可能的问题是:Got Error: NoMethodError: undefined method `fetch_value' for nil:NilClass when trying to create a new record in the rails console
基本上,ActiveRecord(和一般的rails)是靠很多黑魔法工作的,如果你不小心,走出常规一步,世界就开始崩溃。在referenced post的例子中,他们使用了一个“保留字”(查找“ruby reserved words”,也许还有“rails reserved words”)作为db列名。
你在DB中有保留字列表中的东西吗?

相关问题