Skip to content

Instantly share code, notes, and snippets.

@haf
Created June 15, 2011 10:34
Show Gist options
  • Save haf/1026857 to your computer and use it in GitHub Desktop.
Save haf/1026857 to your computer and use it in GitHub Desktop.
How to unit-test exec_get/getter.call
class StrQ < Q
attr_accessor :default
def initialize(question, default = nil, io_source = STDIN, validator = nil)
@question = question
@default = default
@io_source = io_source
@validator = validator || lambda { true }
end
def exec
puts @question
@answer = (io_source.gets || @default) while not @validator.call(@answer)
end
def answer
@answer || @default
end
end
## UNIT TEST:
require 'logirel/q_model'
require 'rspec'
RSpec.configure do |c|
c.mock_with :rspec
end
describe Logirel::StrQ, "in its default mode of operation, when reading props" do
before(:all) { @q = StrQ.new "Q??", "def" }
subject { @q }
it { should respond_to :question }
it { should respond_to :default }
specify { @q.answer.should eql("def") }
specify { @q.question.should eql("Q??") }
end
describe Logirel::StrQ, "when feeding it OK input" do
before(:all) do
@io = StringIO.new "My Answer"
@validator = double('validator')
@validator.should_receive(:call).once
with(an_instance_of(String))
and_return(true)
end
subject { StrQ.new("q?", "def", @io, @validator) }
specify { subject.exec.should eql("My Answer") and subject.answer.should eql("My Answer") }
end
describe Logirel::StrQ, "when feeding it bad input" do
before(:all) do
@io = StringIO.new "My Answer\nAnother Answer"
@validator = double('validator')
@validator.should_receive(:call).exactly(3).times.
with(an_instance_of(String))
and_return(false, false, true)
end
subject { StrQ.new("q?", "def", @io, @validator) }
specify { subject.exec }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment