-
Notifications
You must be signed in to change notification settings - Fork 8
Testing Commands
mosop edited this page Jan 28, 2017
·
11 revisions
Crystal CLI provides several features to test commands without building individual binary executables.
To use the testing features, set the CRYSTAL_CLI_ENV environment variable to test.
ENV["CRYSTAL_CLI_ENV"] = "test"In the test environment, the exit! method does not actually exits. Instead, it returns a Cli::Exit exception. You can get informational values from the exception and test the values.
require "cli"
ENV["CRYSTAL_CLI_ENV"] = "test"
class Smiley < Cli::Command
def run
exit! ":)"
end
end
exit = Smiley.run
exit.success? # true
exit.error? # false
exit.message # :)
exit.code # 0Cli::Spec::Helper provides the exit_command matcher for testing explicit exits with crystal spec.
# test.cr
require "spec"
require "cli"
require "cli/spec"
ENV["CRYSTAL_CLI_ENV"] = "test"
class Smiley < Cli::Command
def run
exit! ":("
end
end
module SmileySpec
include Cli::Spec::Helper
it "works" do
Smiley.run.should exit_command(output: ":)")
end
endOutput:
$ crystal spec test.cr
F
Failures:
1) works
Failure/Error: Smiley.run.should exit_command(output: ":)")
Unmatched output.
expected:
:)
got:
:(
# test.cr:17
Finished in 1.49 milliseconds
1 examples, 1 failures, 0 errors, 0 pending
In the test environment, the :out and :err named IOs are newly created Cli::Ios::Pipe objects, not the standard IOs. So you can read the named IOs to get the output without capturing the standard IOs.
For more information about the named IO, see Using Named IOs.
require "spec"
require "cli"
ENV["CRYSTAL_CLI_ENV"] = "test"
class Smiley < Cli::Command
def run
puts ":)"
end
end
module SmileySpec
include Cli::Spec::Helper
it "works" do
Smiley.run do |cmd|
cmd.out.gets_to_end.should eq ":)\n" # OK
end
end
end