Ruby 用于检查数字的Rspec

Ruby 用于检查数字的Rspec,ruby,rspec,Ruby,Rspec,我是一个ruby新手,我已经成功地提取了ruby的代码,但是为他们编写RSpec似乎有问题。即使阅读了一些教程,也很难理解编写RSpec的方法。有人请帮我写一个输入法,然后我会尝试重构它的休息 RB文件: module RubyOperations class Operations def input(num) RubyOperations.log('Enter a number:[Between 1 to 10]',:BOTH) num = Integer(

我是一个ruby新手,我已经成功地提取了ruby的代码,但是为他们编写RSpec似乎有问题。即使阅读了一些教程,也很难理解编写RSpec的方法。有人请帮我写一个输入法,然后我会尝试重构它的休息

RB文件:

module RubyOperations
  class Operations
    def input(num)
      RubyOperations.log('Enter a number:[Between 1 to 10]',:BOTH)
      num = Integer(gets.chomp)
      raise StandardError if num <= 0 || num > 10
      return num
    rescue StandardError, ArgumentError => e
      RubyOperations.log(e,:ERROR)
    end
  end
end

您可以检查方法输出的类是否等于整数

require 'ruby_final_operations'
  describe 'RubyOperations' do
    describe 'Operations' do
      describe '.input' do
        context 'when number is provided' do
          it 'returns the number provided' do
            expect(RubyOperations.input(num).class).to eq(Integer)
            (or)
            expect(RubyOperations.input(num)).to be_a_kind_of(Integer) 
          end
         end
        end
       end
      end
无论何时写rspec,请记住

如果编写rspec的方法处理数据库中的操作,那么检查数据库是否被操作

或者,如果您正在为任何返回对象的方法编写rspec,则执行如下处理

it 'returns square of a number' do
  expect(square_of_a_number(2).to eq(4)   
end
如果一个方法定义如下

def square_of_a_number(num)
 num*num
end
然后像这样写rspec

it 'returns square of a number' do
  expect(square_of_a_number(2).to eq(4)   
end

对于您知道的任何方法,方法的输出将是硬编码输入或用于方法输入的用户伪造gem,以期望该方法的预期结果

您共享的代码很少有问题:

1在Operations类中,方法输入接收到一个参数,该参数由于以下行而未在任何地方使用:num=Integergets.chomp。基本上,get是等待用户输入的方法,赋值num=。。。重写传递给方法的参数num的值,因此将num参数传递给方法是毫无意义的

2在您的规范示例中,您调用RubyOperations模块上的输入方法,而输入存在于命名空间RubyOperations下的类操作中。此外,方法输入不是类方法,而是实例方法。所以正确的方法调用应该是:RubyOperations::Operations.new.input5

3要运行输入法规范,您需要存根用户输入。RSpec mocks gem可以帮你解决这个问题。它有允许存根方法:allowobject.ToReceive:gets{5}

整个样本将是:

it 'returns the number provided' do
  # instantiate object that we will test
  subject = RubyOperations::Operations.new

  # we stub method 'gets' and whenever it is called we return string "5"
  allow(subject).to receive(:gets) { "5" } 

  # we call method input with argument 1, the argument 1 is pointless as described in point 1) and can be omitted
  expect(subject.input(1)).to eq(5)
end

查看,它可能有助于您检查对象的类型。谢谢..Will Inspect@SebastianPalmathis是我遇到的错误。NameError:未定义的局部变量或方法'num',您以前在spec文件中定义过num吗?在将num变量作为参数传递之前,您需要声明num变量。请声明num或将硬编码值传递给该方法