gpt4 book ai didi

ruby - 如何为逻辑编写 rspec 并编写 mock STDIN

转载 作者:太空宇宙 更新时间:2023-11-03 16:12:48 24 4
gpt4 key购买 nike

我是一个非常新的编码员,正在尝试为测试条件语句/逻辑的类编写 rspec。我开始为它编写 sudo 代码,但我被告知要制作我不知道如何制作的模拟 STDIN。有人可以为类(class)编写 rspec 或者给我一些关于如何创建模拟 STDIN 的想法。我需要帮助为条件语句/逻辑编写 rspec,如果有人可以只为其中一个上下文编写测试,那么我可以在此基础上做休息。

require 'rails_helper'

module BAB::ACA

RSpec.describe partfinder do

describe '#find_part_id' do
let(:face) { create(:face) }

subject { described_class.find_part_id(face) }

context 'When bab con already exists' do
context 'when there are more than one part ids' do
#create part ids

context 'when user input matches an existing id' do
#mock STDIN that matches an existing, subject should equal that id
end

context 'when user input does not match an existing id' do
# mock STDIN that does match existing id, should return failure message
end
end

context 'when there is only one bab part id' do
# subject should equal the one that already exists
end
end

context 'when av con does not yet exist' do
# mock STDIN and make sure subject equals what you mocked
end
end
end

module BAB::ACA

class partfinder

def self.find_part_id(face)
av_con = BAB::Child:Fail.find_by(
face: face
reg: BAB:Child.find_reg
)
if av_con
look_id(face, av_con)
end
else
puts "What is #{face.name} BAB part id? must be 6"
STDIN.gets.chomp
end
end

def self.look_id(face, av_con)
if av_con.part_ids.length > 1
ask_for_id(face, av_con)
else
av.con.part_ids.first
end
end

def self.ask_for_id(face, av_con)
puts "What is #{face.name} BAB part id? "
bab_part_id = STDIN.gets.chomp

unless av.con.part_ids.include?(bab_part_id)
fail 'Entered id doesn't match'
end
bab_part_id
end
end
end

最佳答案

您可以使用 method stubs .

在这种情况下,你想 stub STDIN.gets.chomp,所以你会做这样的事情:

describe '#find_part_id' do
before do
allow(STDIN.gets).to receive(:chomp).and_return(stdin_input)
end

let(:stdin_input) { 'user input from stdin' }
let(:face) { create(:face) }

subject { described_class.find_part_id(face) }

context 'When bab con already exists' do
context 'when there are more than one part ids' do
it 'some test' do
# your test here
end
end

# more contexts...

context 'a context that needs a different stdin_input' do
let(:stdin_input) { 'some different user input from stdin' }

it 'another test' do
# your test here
end
end
end
end

其中 stdin_input 是您希望用户为您的测试输入的字符串。

关于ruby - 如何为逻辑编写 rspec 并编写 mock STDIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56765567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com