运行 RSpec 测试时出现 NoMethodError

NoMethodError when running RSpec test

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

这是我的gem: ~/project/gemz/spec/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 方法中输入的值是否 > 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

我在 rails 的 ruby 还很陌生。谁能指出我正确的方向?感谢任何帮助。

几件事:

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

    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
    

请注意,我已经删除了 self 关键字以向您展示我的第一点的意思 - 现在您编写的测试中的语法 (checkpercentage.method_name) 将正确

此外,请注意,您的代码中存在错误 - 它可以工作,但也不是您想要的。希望您编写的测试将帮助您找到并修复它,如果没有请告诉我们!