Module: Clack::Testing

Defined in:
lib/clack/testing.rb

Overview

First-class test helpers for simulating prompt interactions.

Works with RSpec, Minitest, or any test framework. Provides a DSL for feeding keystrokes to prompts without a real terminal.

Examples:

Basic text prompt

result = Clack::Testing.simulate(Clack.method(:text), message: "Name?") do |p|
  p.type("Alice")
  p.submit
end
assert_equal "Alice", result

Select prompt

result = Clack::Testing.simulate(Clack.method(:select), message: "Pick", options: %w[a b c]) do |p|
  p.down
  p.submit
end
assert_equal "b", result

Multiselect

result = Clack::Testing.simulate(Clack.method(:multiselect), message: "Pick", options: %w[a b c]) do |p|
  p.toggle      # select "a"
  p.down
  p.toggle      # select "b"
  p.submit
end
assert_equal %w[a b], result

Cancellation

result = Clack::Testing.simulate(Clack.method(:text), message: "Name?") do |p|
  p.cancel
end
assert Clack.cancel?(result)

Defined Under Namespace

Classes: KeyQueue, PromptDriver

Constant Summary collapse

KEYS =

Key constants matching what KeyReader returns

{
  enter: "\r",
  escape: "\e",
  ctrl_c: "\u0003",
  ctrl_d: "\u0004",
  up: "\e[A",
  down: "\e[B",
  right: "\e[C",
  left: "\e[D",
  backspace: "\u007F",
  space: " ",
  tab: "\t",
  shift_tab: "\e[Z"
}.freeze

Class Method Summary collapse

Class Method Details

.simulate(prompt_method, **kwargs) {|PromptDriver| ... } ⇒ Object

Simulate a prompt interaction by feeding a predefined key sequence.

Parameters:

  • prompt_method (Method, Proc)

    the Clack method to call (e.g. Clack.method(:text))

  • kwargs (Hash)

    keyword arguments for the prompt

Yields:

Returns:

  • (Object)

    the prompt result



134
135
136
137
138
139
140
141
142
# File 'lib/clack/testing.rb', line 134

def simulate(prompt_method, **kwargs, &block)
  driver = PromptDriver.new
  block.call(driver)

  input = KeyQueue.new(driver.keys.dup)
  output = StringIO.new

  prompt_method.call(**kwargs, input: input, output: output)
end

.simulate_with_output(prompt_method, **kwargs) {|PromptDriver| ... } ⇒ Array(Object, String)

Capture the rendered output of a prompt simulation. Returns both the result and the raw output string.

Parameters:

  • prompt_method (Method, Proc)

    the Clack method to call

  • kwargs (Hash)

    keyword arguments for the prompt

Yields:

Returns:

  • (Array(Object, String))
    result, output_string


151
152
153
154
155
156
157
158
159
160
# File 'lib/clack/testing.rb', line 151

def simulate_with_output(prompt_method, **kwargs, &block)
  driver = PromptDriver.new
  block.call(driver)

  input = KeyQueue.new(driver.keys.dup)
  output = StringIO.new

  result = prompt_method.call(**kwargs, input: input, output: output)
  [result, output.string]
end