### Complete Maxitest Integration Example Source: https://context7.com/grosser/maxitest/llms.txt A comprehensive Ruby example showcasing Maxitest features for integration testing. It includes setup with `let_all`, `before`, `around`, environment variable manipulation with `with_env`, pending tests, and assertions. Requires 'maxitest/autorun', 'maxitest/timeout', and 'maxitest/threads'. ```ruby require "maxitest/autorun" require "maxitest/timeout" require "maxitest/threads" Maxitest.timeout = 30 Maxitest.static_class_order = true describe "CompleteExample" do let_all(:database) do db = Database.new db.migrate db end let!(:user) { User.create(name: "Test User") } before :all do @server = start_test_server end before do @client = HTTPClient.new(@server.url) end after do @client.close end around do |test| with_env API_KEY: "test" do test.call end end context "with authenticated user" do it "creates a record" do output = capture_stdout do response = @client.post("/users", user.to_json) puts "Created user #{response.body}" end _(output).must_include "Created user" _(User.count).must_equal 1 end pending "future feature", if: ENV["CI"] do _(unimplemented_api).must_equal true end end xit "skipped test for later" do _(incomplete_feature).must_equal 42 end end ``` -------------------------------- ### Basic Maxitest Setup and Usage in Ruby Source: https://context7.com/grosser/maxitest/llms.txt Demonstrates the fundamental setup for using Maxitest with Minitest. It includes the necessary require statement and a basic test structure using `describe` and `it` blocks. ```ruby require "maxitest/autorun" describe MyClass do describe "#my_method" do it "passes" do _(MyClass.new.my_method).must_equal 1 end end end ``` -------------------------------- ### Maxitest let_all for Shared Setup Across Tests in Ruby Source: https://context7.com/grosser/maxitest/llms.txt Shows how to use `let_all` in Maxitest to define setup that is executed only once for all tests within a class and its subclasses. This is useful for expensive resources like database connections. ```ruby require "maxitest/autorun" describe "ExpensiveSetup" do let_all(:database) do # Executes ONCE for all tests in this class and subclasses db = Database.new db.seed_with_test_data db end it "uses shared database" do _(database.users.count).must_equal 100 end it "shares same instance" do _(database.object_id).must_equal database.object_id end context "nested context" do it "inherits let_all from parent" do _(database.users.first.name).wont_be_nil end end end ``` -------------------------------- ### Maxitest Capture Stdout Example Source: https://github.com/grosser/maxitest/blob/master/README.md Provides an example of capturing standard output (stdout) using Maxitest's 'capture_stdout' helper. It demonstrates how to execute code that prints to stdout and then assert the captured output. ```Ruby output = capture_stdout { puts 1 } _(output).must_equal "1\n" ``` -------------------------------- ### Basic Maxitest Usage with Ruby Source: https://github.com/grosser/maxitest/blob/master/README.md Demonstrates the basic setup for using Maxitest in a Ruby project. It requires the 'maxitest/autorun' library and shows a simple test case using 'describe' and 'it' blocks with a 'must_equal' assertion. ```Ruby require "maxitest/autorun" # ... normal minitest tests ... describe MyClass do describe "#my_method" do it "passes" do _(MyClass.new.my_method).must_equal 1 end end end ``` -------------------------------- ### Install Maxitest Gem Source: https://github.com/grosser/maxitest/blob/master/README.md Installs the Maxitest gem using the RubyGems package manager. This is the primary method for adding Maxitest to your project. ```Bash gem install maxitest ``` -------------------------------- ### Run Maxitest tests using mtest command line tool Source: https://context7.com/grosser/maxitest/llms.txt Provides an example of how to use the `mtest` command-line tool, which is the executable for running Maxitest test suites. The example shows a basic command to execute a specific test file. The `mtest` tool allows developers to run tests directly from the terminal, offering options for specifying test files, directories, or filtering tests based on various criteria. ```bash # Run a specific test file mtest spec/my_test.rb ``` -------------------------------- ### Maxitest Pending Block Example Source: https://github.com/grosser/maxitest/blob/master/README.md Illustrates how to use the 'pending' block in Maxitest to mark tests that are known to be incomplete or intentionally failing. It shows how to provide a reason for the pending test and how to conditionally skip it based on environment variables. ```Ruby pending "need to fix" do # Test code here end pending "need to fix", if: ENV["CI"] do # Test code here, only skipped on CI end ``` -------------------------------- ### Maxitest CLI Commands Source: https://context7.com/grosser/maxitest/llms.txt Demonstrates various command-line options for the 'mtest' tool, including running specific tests, directories, changed files, verbose output, and accessing version/help information. No external dependencies are required beyond the 'maxitest' gem installation. ```bash mtest spec/my_test.rb:25 mtest spec/integration/ mtest --changed mtest spec/my_test.rb -v mtest --version mtest --help ``` -------------------------------- ### Maxitest Context Alias Example Source: https://github.com/grosser/maxitest/blob/master/README.md Demonstrates the usage of 'context' as an alias for 'describe' in Maxitest, allowing for more expressive test organization. It shows a nested structure with 'before' blocks. ```Ruby describe "#my_method" do context "with bad state" do before { errors += 1 } it "fails" # ... test implementation ... end end ``` -------------------------------- ### Maxitest around - Wrapping Test Execution in Ruby Source: https://context7.com/grosser/maxitest/llms.txt Illustrates how to use the `around` block in Maxitest to wrap the execution of individual tests. This allows for setup and teardown logic that surrounds the test's execution, such as managing temporary directories. ```ruby require "maxitest/autorun" describe "AroundTest" do around do |test| # Setup code before test Dir.mktmpdir do |dir| Dir.chdir(dir) do test.call # Execute the actual test end end # Cleanup happens automatically when block exits end it "runs in temporary directory" do _(Dir.pwd).must_match /tmp/ File.write("test.txt", "content") _(File.exist?("test.txt")).must_equal true end it "gets fresh directory each time" do _(Dir.entries(".")).must_equal [".", ".."] end end ``` -------------------------------- ### Organize tests using context in Ruby Source: https://context7.com/grosser/maxitest/llms.txt Illustrates how to use the `context` method in Maxitest for descriptive test organization. `context` allows grouping related tests under a common description, improving test suite readability and structure. It supports `before` and `after` hooks that are executed within the scope of the context, enabling setup and teardown logic for specific groups of tests. This is particularly helpful for testing different states or scenarios of a feature. ```ruby require "maxitest/autorun" describe "UserAuthentication" do let(:user) { User.new(email: "test@example.com") } context "with valid credentials" do before { user.password = "secure123" } it "logs in successfully" do _(user.authenticate("secure123")).must_equal true end it "returns auth token" do token = user.login("secure123") _(token).wont_be_nil end end context "with invalid credentials" do before { user.password = "secure123" } it "rejects wrong password" do _(user.authenticate("wrong")).must_equal false end it "raises error on login" do _ { user.login("wrong") }.must_raise AuthenticationError end end end ``` -------------------------------- ### Utilize implicit subject with Calculator in Ruby Source: https://context7.com/grosser/maxitest/llms.txt Explains and demonstrates the concept of an implicit subject in Maxitest, often used with the `implicit_subject` extension. When `subject` is used within a test, it automatically refers to an instance of the class being described (e.g., `Calculator.new`). This reduces boilerplate code by eliminating the need to explicitly instantiate the object under test in every test case. The example shows accessing methods of the implicit subject directly. ```ruby require "maxitest/autorun" require "maxitest/implicit_subject" class Calculator def add(a, b) a + b end end describe Calculator do # subject is automatically set to Calculator.new it "adds numbers" do _(subject.add(2, 3)).must_equal 5 end it "uses implicit subject" do _(subject).must_be_instance_of Calculator end end ``` -------------------------------- ### Configure timeout protection in Maxitest Ruby Source: https://context7.com/grosser/maxitest/llms.txt Details how to implement and configure timeout protection for tests in Maxitest. A global timeout can be set using `Maxitest.timeout = seconds`. Individual tests can override this by defining a `maxitest_timeout` method within their scope, returning the desired timeout in seconds or `false` to disable the timeout. This feature helps prevent tests from hanging indefinitely, ensuring the test suite remains responsive. The example shows setting a global timeout and overriding it for specific tests. ```ruby require "maxitest/autorun" require "maxitest/timeout" Maxitest.timeout = 10 # Global timeout of 10 seconds describe "TimeoutTests" do it "fails if test takes too long" do sleep 0.1 # Completes quickly _(1).must_equal 1 end # This would fail with TestCaseTimeout after 10 seconds: # it "hangs forever" do # sleep 100 # end # Override timeout per test def maxitest_timeout 2 # This test times out after 2 seconds end it "has custom timeout" do sleep 0.5 _(true).must_equal true end # Disable timeout for debugging describe "DebugTests" do def maxitest_timeout false # No timeout, useful for debugger end it "can run indefinitely" do # debugger would work here _(1).must_equal 1 end end end ``` -------------------------------- ### Maxitest before :all and after :each Hooks in Ruby Source: https://context7.com/grosser/maxitest/llms.txt Demonstrates the usage of `before :all`, `before`, and `after` hooks in Maxitest. `before :all` runs once before all tests in the scope, while `before` and `after` run before and after each individual test, respectively. ```ruby require "maxitest/autorun" describe "HookTest" do before :all do # Runs once before all tests in this class @server = TestServer.start(port: 3000) end before do # Runs before each test @client = HTTPClient.new("http://localhost:3000") end after do # Runs after each test @client.close if @client end it "connects to server" do response = @client.get("/health") _(response.status).must_equal 200 end it "handles requests" do response = @client.post("/api/data", {key: "value"}) _(response.body).must_include "success" end end ``` -------------------------------- ### Maxitest let! for Eager Evaluation in Ruby Source: https://context7.com/grosser/maxitest/llms.txt Illustrates the use of `let!` in Maxitest for eager evaluation of helper methods. The helper defined with `let!` is executed before each test, ensuring its value is available immediately and its side effects are applied. ```ruby require "maxitest/autorun" describe "DatabaseTest" do let(:user) { User.new(name: "Alice") } let!(:saved_user) { user.save; user } # Executes before each test automatically it "has user already saved" do _(saved_user.persisted?).must_equal true _(User.count).must_equal 1 end it "can be accessed in another test" do _(saved_user.name).must_equal "Alice" _(User.count).must_equal 1 # Each test gets fresh let! execution end end ``` -------------------------------- ### Maxitest with_env Usage Source: https://github.com/grosser/maxitest/blob/master/README.md Shows how to use the 'with_env' helper in Maxitest to temporarily change environment variables during test execution. This is useful for testing code that relies on specific environmental settings. ```Ruby with_env FOO: "bar" do # Code that runs with FOO="bar" end # Can also be used as an around block with_env FOO: "bar" ``` -------------------------------- ### Maxitest pending - Conditional Test Skipping in Ruby Source: https://context7.com/grosser/maxitest/llms.txt Demonstrates the `pending` functionality in Maxitest for conditionally skipping tests. It shows how to mark tests as pending with a reason, or skip them based on a condition like an environment variable. ```ruby require "maxitest/autorun" describe "PendingTests" do it "skips when test fails" do pending "API not implemented yet" do _(unimplemented_method).must_equal 42 end # Test is skipped because it fails end it "fails when test passes" do # This will raise Minitest::Assertion: "Test is fixed, remove `pending`" # pending do # _(2 + 2).must_equal 4 # end end it "conditionally skips on CI" do pending "Flaky on CI", if: ENV["CI"] do _(external_api_call).must_equal expected_value end # Only skips when CI=true, runs normally locally end it "runs when condition is false" do pending "Not actually pending", if: false do _(1 + 1).must_equal 2 end # This runs normally because if: false end end ``` -------------------------------- ### Capture stdout and stderr in Ruby Source: https://context7.com/grosser/maxitest/llms.txt Demonstrates how to capture standard output (stdout) and standard error (stderr) independently using the `capture_stdout` and `capture_stderr` methods provided by Maxitest. These methods are useful for testing code that produces output to the console. They take a block of code and return the captured output as a string. Any output not intended for the captured stream will pass through. ```ruby require "maxitest/autorun" describe "CaptureTests" do it "captures stdout only" do output = capture_stdout do puts "This goes to stdout" warn "This goes to stderr" # Not captured end _(output).must_equal "This goes to stdout\n" end it "captures stderr only" do output = capture_stderr do puts "This goes to stdout" # Not captured warn "This is a warning" end _(output).must_equal "This is a warning\n" end it "captures both separately" do stdout = capture_stdout { puts "out" } stderr = capture_stderr { warn "err" } _(stdout).must_equal "out\n" _(stderr).must_equal "err\n" end end ``` -------------------------------- ### Maxitest with_env - Environment Variable Management in Ruby Source: https://context7.com/grosser/maxitest/llms.txt Explains how to use `with_env` in Maxitest to manage environment variables during test execution. It covers setting variables for an entire test class or temporarily within a specific test block, ensuring automatic restoration. ```ruby require "maxitest/autorun" describe "EnvironmentTests" do # Class-level: sets env for all tests in describe block with_env API_KEY: "test_key", DEBUG: "true" it "has env variables set" do _(ENV["API_KEY"]).must_equal "test_key" _(ENV["DEBUG"]).must_equal "true" end it "uses with_env in test body" do original = ENV["PATH"] with_env PATH: "/custom/path", NEW_VAR: "value" do _(ENV["PATH"]).must_equal "/custom/path" _(ENV["NEW_VAR"]).must_equal "value" end # Environment is restored after block _(ENV["PATH"]).must_equal original _(ENV["NEW_VAR"]).must_be_nil end end ``` -------------------------------- ### Skip tests without hooks using xit in Ruby Source: https://context7.com/grosser/maxitest/llms.txt Shows how to use `xit` in Maxitest to skip a test case. Unlike `it`, `xit` prevents the test from running entirely, including any associated `before` or `after` hooks defined within its scope or parent contexts. This is useful for temporarily disabling tests without removing them from the codebase, often used during development or when a feature is incomplete. The code within an `xit` block and its hooks will not be executed. ```ruby require "maxitest/autorun" describe "SkippingTests" do before do @expensive_setup = perform_expensive_operation end after do cleanup_expensive_operation(@expensive_setup) end it "runs normally" do _(1 + 1).must_equal 2 end xit "skips without running setup/teardown" do # Neither before nor after hooks are called _(unimplemented_feature).must_equal 42 end it "runs this one too" do _(@expensive_setup).wont_be_nil end end ``` -------------------------------- ### Maxitest Disable Interrupt Handling Source: https://github.com/grosser/maxitest/blob/master/README.md Explains how to disable Maxitest's interrupt handling by setting the environment variable 'MAXITEST_NO_INTERRUPT' to 'true'. This is a workaround for potential 'stack level too deep' errors related to the minitest-reporters gem. ```Bash ENV["MAXITEST_NO_INTERRUPT"] = "true" ``` -------------------------------- ### Detect and manage thread leaks in Maxitest Ruby Source: https://context7.com/grosser/maxitest/llms.txt Explains Maxitest's thread leak detection capabilities, enabled by requiring `maxitest/threads`. The framework automatically checks if any threads are left running after a test completes and fails the test if extra threads are detected. It also provides helper methods like `maxitest_wait_for_extra_threads` to gracefully wait for threads to finish and `maxitest_kill_extra_threads` to forcefully terminate them. This prevents background threads from interfering with subsequent tests or leaking resources. ```ruby require "maxitest/autorun" require "maxitest/threads" describe "ThreadTests" do it "passes with no extra threads" do result = calculate_something _(result).must_equal 42 end it "fails if threads are left running" do # This would fail: "Test left 1 extra threads" # Thread.new { sleep 10 } end it "cleans up threads properly" do thread = Thread.new { sleep 0.1 } thread.join # Proper cleanup _(thread.alive?).must_equal false end it "uses helper to wait for threads" do Thread.new { sleep 0.01 } maxitest_wait_for_extra_threads # Wait for threads to finish end it "uses helper to kill threads" do Thread.new { sleep 10 } maxitest_kill_extra_threads # Forcefully kill extra threads end end ``` -------------------------------- ### Ensure static test class order in Maxitest Ruby Source: https://context7.com/grosser/maxitest/llms.txt Describes how to enforce a static order for test classes in Maxitest by setting `Maxitest.static_class_order = true`. By default, Maxitest randomizes the order in which test classes are executed to catch potential ordering dependencies. When this option is enabled, test classes will run in the exact order they are defined in the code. This can be useful for debugging or when a specific, non-random execution sequence is required for tests. ```ruby require "maxitest/autorun" # Disable random class ordering Maxitest.static_class_order = true describe "FirstTest" do it "always runs first" do _(1).must_equal 1 end end describe "SecondTest" do it "always runs second" do _(2).must_equal 2 end end # Without static_class_order, test classes run in random order # With static_class_order = true, they run in definition order ``` -------------------------------- ### Enforce sequential test execution with order_dependent! in Ruby Source: https://context7.com/grosser/maxitest/llms.txt Demonstrates the use of `order_dependent!` in Maxitest to ensure that tests within a describe block run in the order they are defined. By default, Maxitest shuffles the order of tests. Calling `order_dependent!` disables this shuffling for the specific describe block, making test execution predictable and allowing tests to rely on the state set by preceding tests. This is useful for testing stateful operations or workflows. ```ruby require "maxitest/autorun" describe "StatefulTests" do order_dependent! # Tests run in definition order @@counter = 0 it "runs first and sets state" do @@counter = 1 _(@@counter).must_equal 1 end it "runs second and reads state" do @@counter += 1 _(@@counter).must_equal 2 end it "runs third and verifies state" do _(@@counter).must_equal 2 end end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.