Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- # detective
- # Tests by asking the user questions
- #
- # NOTE: requires ruby 1.9.2 and the rainbow gem.
- #
- # Usage:
- # detective [list of ruby test files]
- #
- # Syntax:
- # describe "A test" do
- # instruct "Go to google"
- # ask("What is written on the first button?").expect("Google Search")
- # end
- #
- #
- require 'fiber'
- require 'rainbow'
- module Detective
- # Ask question. e.g.
- # ask "Where were you last night?"
- def ask(question)
- @last_question = question
- @last_result = Fiber.yield [:ask, question]
- return self
- end
- # Instruct the user. e.g.
- # instruct "You have the right to remain silent"
- def instruct(question)
- Fiber.yield [:instruct, question]
- return self
- end
- # Expect a result from the last question. e.g.
- # ask("When did you last see M. Ratchett alive?").expect("last evening")
- def expect(result)
- if (@last_result||'').strip != result.to_s.downcase
- Fiber.yield [:fail, @last_question, @last_result, result]
- end
- end
- # Describe a test. e.g.
- # describe("The suspect") { ask("How many fingers am i holding up?").expect(1) }
- def describe test, &block
- Fiber.yield [:describe, test]
- yield
- Fiber.yield [:describe_end, test]
- end
- alias_method :it, :describe
- end
- def run_suite(files)
- fib = Fiber.new do
- include Detective
- files.each { |f| require f }
- end
- total_test = 0
- total_pass = 0
- test_results = []
- begin
- result = nil
- describe_stack = []
- while (command = fib.resume(result)) and !command.nil? and command != :end
- result = nil
- case command[0]
- when :instruct
- if describe_stack[-1][1]
- puts "#{command[1]} [press RETURN to continue]"
- result = STDIN.readline
- end
- when :ask
- if describe_stack[-1][1]
- puts "#{command[1]}: "
- result = STDIN.readline.downcase
- end
- when :describe
- describe_stack << [command[1], true]
- puts "\n#{describe_stack.map{|d|d[0]}.join(' ')}.\n"
- total_test += 1
- when :describe_end
- test_results << ["#{describe_stack.map{|d|d[0]}.join(' ')}.", describe_stack[-1][1]]
- total_pass += 1 if describe_stack.pop[1]
- when :fail
- describe_stack[-1][1] = false
- end
- end
- rescue FiberError
- rescue Exception => e
- puts e.inspect
- puts e.backtrace
- end
- puts "\n"
- test_results.reverse.each do |test|
- puts test[0].color(test[1] ? :green : :red)
- end
- puts "\n#{total_pass} / #{total_test} Tests passed".color(total_pass == total_test ? :green : :red)
- exit total_pass == total_test ? 0 : 1
- end
- run_suite(ARGV)
Add Comment
Please, Sign In to add comment