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
Here's my spec.
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
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?
Thanks in advance!
require_relative 'my_file.rb'line beneath theexpectit did work. How ever, this still doesn't assure that thegets,method is being called. If I changed the value ofMy_nameto anything else besides gets, the test still passes. I need the unit test to fail ifgetsisn't being called. I updated my code. - SalceCodecexpect(My_name).to eq("John Doe\n")after requiring the file. However, the test will fail due to some interaction betweenrequire_relativeand standard input. Overall, you're going down a bad path in executing code outside classes and trying to test it by requiring it in the test. I'd like to suggest a good path, but it's hard to do it for your example. What is the point of assigninggetsto a constant in a required file anyway? Perhaps more context would help. - Dave Schweisguthgetsmethod and I want them to declare a variable and initialize it withgetsand submit the answer via an online compiler. I use unit test to check if there correct (Pass/Fail). The only reason theMy_namevariable is a constant is because I need it to be global in order to access it from the spec file. I want to be able to create a Unit Test based on if the user declared a variable and initialized it with the gets method. - SalceCodec