Reputation: 91
How do I design a RSpec test for assigning a gets.chomp
method to an instance variable?
def choose
puts "Please enter the type you want:"
@type = gets.chomp
puts "Thank you, now please enter how many of those you want:"
@quantity = gets.chomp
end
Upvotes: 2
Views: 2126
Reputation: 2558
You can use stubs/mocks for that. But the main question is: where did you place def choose
? It's important since i'll stub it's calls on some object.
Let imagine you have this method in class Item
:
class Item
def choose
puts "Please enter the type you want:"
@type = gets.chomp
puts "Thank you, now please enter how many of those you want:"
@quantity = gets.chomp
end
end
Then i'll be able to stub gets
and chomp
calls to simulate user's input:
RSpec.describe Item do
describe '#choose' do
before do
io_obj = double
expect(subject)
.to receive(:gets)
.and_return(io_obj)
.twice
expect(io_obj)
.to receive(:chomp)
.and_return(:type)
expect(io_obj)
.to receive(:chomp)
.and_return(:quantity)
end
it 'sets @type and @quantity according to user\'s input' do
subject.choose
expect(subject.instance_variable_get(:@type)).to eq :type
expect(subject.instance_variable_get(:@quantity)).to eq :quantity
end
end
end
Upvotes: 2