module RatatuiRuby::TestHelper::Terminal
Terminal setup and buffer inspection for TUI tests.
Testing TUIs against a real terminal is slow, flaky, and hard to automate. Initializing, cleaning up, and inspecting terminal state by hand is tedious.
This mixin wraps a headless test terminal. It handles setup, teardown, and provides methods to query buffer content, cursor position, and cell styles.
Use it to write fast, deterministic tests for your TUI applications.
Example
class MyTest < Minitest::Test include RatatuiRuby::TestHelper def test_rendering with_test_terminal(80, 24) do MyApp.new.run_once assert_includes buffer_content.join, "Hello" end end end
Public Instance Methods
Source
# File lib/ratatui_ruby/test_helper/terminal.rb, line 116 def buffer_content RatatuiRuby.get_buffer_content.split("\n") end
Current content of the terminal buffer as an array of strings. Each string represents one row.
Example
buffer_content # => ["Row 1 text", "Row 2 text", ...]
Source
# File lib/ratatui_ruby/test_helper/terminal.rb, line 135 def cursor_position x, y = RatatuiRuby.get_cursor_position { x:, y: } end
Source
# File lib/ratatui_ruby/test_helper/terminal.rb, line 160 def get_cell(x, y) RatatuiRuby.get_cell_at(x, y) end
Source
# File lib/ratatui_ruby/test_helper/terminal.rb, line 182 def print_buffer puts _render_buffer_with_ansi end
Prints the current buffer to STDOUT with full ANSI colors. Useful for debugging test failures.
Example
with_test_terminal do MyApp.new.render print_buffer # see exactly what would display end
Source
# File lib/ratatui_ruby/test_helper/terminal.rb, line 66 def with_test_terminal(width = 80, height = 24, **opts) # Defensive cleanup: reset any stale session state from previous test failures RatatuiRuby.instance_variable_set(:@tui_session_active, false) # Extract and resolve viewport viewport_param = opts[:viewport] viewport = case viewport_param when nil then RatatuiRuby::Terminal::Viewport.fullscreen when RatatuiRuby::Terminal::Viewport then viewport_param end RatatuiRuby.init_test_terminal(width, height, viewport.type.to_s, viewport.height) # Flush any lingering events from previous tests while (event = RatatuiRuby.poll_event) && !event.none?; end RatatuiRuby.stub :init_terminal, nil do RatatuiRuby.stub :restore_terminal, nil do @_ratatui_test_terminal_active = true timeout = opts.fetch(:timeout, 2) if timeout Timeout.timeout(timeout) do yield end else yield end ensure @_ratatui_test_terminal_active = false end end ensure RatatuiRuby.restore_terminal end
Initializes a test terminal context with specified dimensions. Restores the original terminal state after the block executes.
- width
-
Integer width of the test terminal (default: 80).
- height
-
Integer height of the test terminal (default: 24).
- timeout
-
Integer maximum execution time in seconds (default: 2). Pass
nilto disable.
Example
with_test_terminal(120, 40) do # render and test your app end