Reputation: 5058
I have a code snippet in which i am terminating the program when i receive exit
input from STDIN
using gets. How do i write the rspec test case for the same.
Below is the code snippet.
class CommandProcessor
attr_accessor :input
attr_accessor :operation
def parser
while true
input = gets.chomp
operation = input.split(' ')[0]
param = input.split(' ')[1]
if operation.eql? 'exit'
exit
end
end
end
end
Below is my attempt.
describe "CommandProcessor" do
it "will exit on input exit" do
cmd = CommandProcessor.new
cmd.parser
expect { it_will_exit }.raise_exception(SystemExit)
end
end
UPDATE
I tried Leonid Mirsky's method before and got this error :
lib/calculator.rb:37:in `parser': undefined method `chomp' for nil:NilClass (NoMethodError)
Upvotes: 0
Views: 143
Reputation: 831
You can stub the gets
method on the cmd object itself.
Use the following spec code:
describe "CommandProcessor" do
it "will exit on input exit" do
cmd = CommandProcessor.new
cmd.stub(:gets) {"exit\n"}
expect { cmd.parser }.to raise_error SystemExit
end
end
Upvotes: 1