带有RSpec NoMethodError的Ruby:nil:NilClass的未定义方法长度

时间:2018-09-29 11:12:20

标签: ruby rspec

我是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

第3个文件-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”来进行测试。

1 个答案:

答案 0 :(得分:0)

有几个问题:

使用未使用的参数调用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.