使用 RSpec 用 get 测试用户输入 [英] Using RSpec to test user input with gets

查看:39
本文介绍了使用 RSpec 用 get 测试用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用 RSpec 和 Ruby 进行单元测试的新手,我有一个关于如何测试我的代码是否使用 gets 方法但不提示用户输入的问题.

I'm new to Unit Testing using RSpec and Ruby and I have a question on how to test if my code is using the gets method, but without prompting for user input.

这是我要测试的代码.这里没什么疯狂的,只是一个简单的一个班轮.

Here is the code I'm trying to test. Nothing crazy here, just a simple one liner.

my_file.rb

My_name = gets

这是我的规格.

require 'stringio'

def capture_name
    $stdin.gets.chomp
end

describe 'capture_name' do
    before do
        $stdin = StringIO.new("John Doe\n")
    end

    after do 
        $stdin = STDIN
    end

    it "should be 'John Doe'" do 
        expect(capture_name).to be == 'John Doe'
        require_relative 'my_file.rb'
    end
end

现在这个规范有效,但是当我运行代码时,它会提示用户输入.我不希望它这样做.我想简单地测试是否正在调用获取方法并可能模拟用户输入.不确定如何在 RSpec 中实现这一点.在 Python 中,我会使用 unittest.mock 在 RSpec 中是否有类似的方法?

Now this spec works, but when I run the code it prompts for user input. I don't want it to do that. I want to simply test if the gets method is being called and possibly mock the user input. Not to sure how to achieve this in RSpec. In Python I would utilize unittest.mock is there a similar method in RSpec?

提前致谢!

推荐答案

这里是如何使用返回值存根 gets.

Here's how you could stub gets with your return value.

require 'rspec'

RSpec.describe do
  describe 'capture_name' do
    it 'returns foo as input' do
      allow($stdin).to receive(:gets).and_return('foo')
      name = $stdin.gets

      expect(name).to eq('food')
    end
  end
end

Failures:

  1)   should eq "food"
     Failure/Error: expect(name).to eq('food')

       expected: "food"
            got: "foo"

       (compared using ==)

要测试是否正在调用某些东西(例如函数),您可以使用 expect($stdin).to receive(:gets).with('foo') 来确保它正在被调用用正确的参数调用(一次).此场景中的期望线必须位于 name = $stdin.gets 之前.

To test if something is being called (such as a function) you can use expect($stdin).to receive(:gets).with('foo') to ensure it is being called (once) with the right args. The expectation line in this scenario has to go before name = $stdin.gets.

这篇关于使用 RSpec 用 get 测试用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆