【问题标题】:Ruby with RSpec NoMethodError: undefined method length for nil:NilClass带有 RSpec NoMethodError 的 Ruby:nil:NilClass 的未定义方法长度
【发布时间】:2018-09-29 11:12:19
【问题描述】:

我是 Ruby 和 RSpec 的新手,试图为字符串长度编写一个单位大小写。我有3个rb文件如下 1.调用文件

require_relative 'ruby_final_operations'
require_relative 'ruby_helper'
require 'uri'
require 'open-uri'
require 'prime'
module RubyOperations
 # Public: Various commands for the user to interact with RubyCommand.
  class Command
    res = RubyOperations::Operations.new
res.letter_count(res.inputstr)

第二个文件 - 方法实现

    require_relative 'ruby_helper'
require 'logger'
$FILE_LOG = RubyOperations.create_log(File.expand_path('~/RubyOperations_LOG.log'), Logger::DEBUG)
$STD_LOG = RubyOperations.create_log(nil, Logger::INFO)
module RubyOperations
class Operations

def inputstr
      RubyOperations.log('Enter the String:[Length 20]',:BOTH)
      @str = gets.chomp
      raise StandardError if @str =~ /\d/ || @str.empty? || @str.length > 20
    rescue StandardError,ArgumentError => e
      RubyOperations.log(e,:ERROR)
    end

def letter_count(str)
    result = @str.length
      RubyOperations.log("The number of letters in the string: #{result}",:BOTH)
end

第三个文件 - RSpec

require 'ruby_final_operations'

describe 'RubyOperations' do
  describe 'Operations' do
   subject = RubyOperations::Operations.new
describe '.letter_count' do
     context 'when operation is provided' do
      it 'returns letter count' do
        allow(subject.letter_count("hello").to receive(:result).and_return(5)
      end
    end
   end

问题在于,在第二个文件中,他的参数是“str”,但存储的键入字符串是“@str”。 如何从 rspec 文件中传递字符串 'hello' 来测试它。

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    有几个问题:

    使用未使用的参数调用 instance_method

    def letter_count #get rid of argument, the argument does nothing, 
                     #basically it looks you added the argument, 
                     # just, so you can call the other method there.
    

    让你的主要内容简单,顺序清晰

    res.inputstr
    res.letter_count
    

    但是关于你的实际问题,在你的测试中你用错误的方法改变了错误的东西

    allow(subject.letter_count("hello").to receive(:result).and_return(5)
    # letter count should do the log entry, not return five, at least that what your method say
    

    所以你可能想在测试 letter_count 方法之前设置@str。

     subject.instance_variable_set("hello")
     # then test for what you expect the method to return
     expect(subject.letter_count).to eq(5)
     # this specific test will fail, because you are doing a log entry, and not return the length on letter_count.
    

    【讨论】:

    • 谢谢,能够修复:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2014-09-26
    • 2017-12-09
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多