运行RSpec测试时的NoMethodError

时间:2015-03-21 16:47:37

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

我在尝试使用RSpec测试我创建的gem时遇到错误NoMethodError。

这是我的宝石: 〜/项目/ gemz /规格/ LIB / checksomething.rb

class Checkpercentage

  #1) what is  x% of y?
  def self.findAmount(rate, base)
    resultAmount = rate * base/100
    return resultAmount
  end 

  #2) x is what percentage of y?
  def self.findPercent(amount, base)
    resultPercent = amount/base * 100
    return resultPercent
  end

  #3) x is y% of what number?
  def self.findBase(amount, rate)
    resultBase = amount/rate *100
    return resultBase
  end

end # End Module

这是我的rspec测试文件: ./project/gemz/spec/lib/checkpercentage_spc.rb

require "spec_helper"
require "checksomething"

RSpec.describe Checkpercentage, '#intNum' do
  context "with no integer entered" do
    it "must be a number" do
      checkpercentage = Checkpercentage.new
      checkpercentage.findPercent(100, 200)
      expect(checkpercentage.intNum) > 0
    end
  end
end

我想测试findPercentage方法中的enterend值是否为> 0.但是,当我在终端中运行rspec命令( rspec spec / lib / checkpercentage_spc.rb )时,会出现以下错误:

Failures:

1) Checkpercentage#intNum with no integer entered must be a number
   Failure/Error: checkpercentage.findPercent(100, 200)
   NoMethodError: undefined method `findPercent' for #<Checkpercentage:0x9956ca4>
   # ./spec/lib/checkpercentage_spc.rb:8:in `block (3 levels) in <top (required)>'

Finished in 0.00089 seconds (files took 0.17697 seconds to load)
1 example, 1 failure

Failed examples:
    rspec ./spec/lib/checkpercentage_spc.rb:6 # Checkpercentage#intNum with no integer entered must be a number

我对铁轨上的红宝石很新。有人能指出我正确的方向吗?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

有几件事:

  1. 正如Santhosh写的那样,你声明方法的方式(使用self)会使ClassCheckpercentage)本身成为所有方法。如果您希望在instanceCheckpercentage.new)上调用它们,则必须从声明中删除self
  2. 什么是intNum(看起来像Java但它在Ruby中不存在)?如果我理解正确,您要检查findPercent(amount, base)是否返回正数。在这种情况下,the right RSpec syntaxexpect(checkpercentage.findPercent(100, 200)).to be > 0
  3. Ruby a)camelCase避免使用camel_case,b)方法返回已执行的最后一行的结果。这意味着您可以按如下方式重写代码:

    class Checkpercentage
    
      #1) what is  x% of y?
      def find_amount(rate, base)
        rate * base/100
      end 
    
      #2) x is what percentage of y?
      def find_percent(amount, base)
        amount/base * 100
      end
    
      #3) x is y% of what number?
      def find_base(amount, rate)
        amount/rate * 100
      end
    
    end # end Module
    
  4. 请注意,我已删除了self个关键字,以向您展示我的第一点意思 - 现在您编写的测试中的语法(checkpercentage.method_name)将是正确的

    另外请注意,您的代码中存在一个错误 - 它可以运行但不是您想要的。希望你写的测试能帮助你找到并修复它,如果不让我们知道的话!