### Install Magic Test Generator
Source: https://github.com/bullet-train-co/magic_test/blob/main/README.md
Runs the Magic Test installation generator to set up basic system tests and configuration. This generator creates a sample test file and modifies layout views.
```bash
bundle install
rails g magic_test:install
```
--------------------------------
### RSpec Manual Integration for MagicTest::Support
Source: https://github.com/bullet-train-co/magic_test/wiki/NameError:-undefined-local-variable-or-method-'magic_test'
This shows how to manually include MagicTest::Support within an RSpec test file. This is a workaround for cases where Magic Test's automatic setup might not be functioning correctly, preventing the `magic_test` helper from being available. The specific implementation might vary depending on the RSpec configuration.
```ruby
include MagicTest::Support
```
--------------------------------
### Install Magic Test Gem
Source: https://github.com/bullet-train-co/magic_test/blob/main/README.md
Adds the Magic Test gem to your application's Gemfile, enabling its testing functionalities. This is a prerequisite for using Magic Test.
```ruby
gem 'magic_test', group: :test
```
--------------------------------
### Initialize Session Storage Key 'testingOutput'
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_storage.html
This JavaScript function checks if the 'testingOutput' item exists in the browser's session storage. If it does not exist (is null), it initializes it by storing an empty JSON array. This is useful for ensuring a consistent starting point for storing data in session storage.
```javascript
function initializeStorage() {
if (sessionStorage.getItem("testingOutput") == null) {
sessionStorage.setItem("testingOutput", JSON.stringify([]));
}
}
```
--------------------------------
### Start Mutation Observation (JavaScript)
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_mutation_observer.html
Starts the MutationObserver to observe changes in the entire document. It sets the target element from the event and configures observation options including attributes, character data, child list, and subtree. This function relies on a pre-initialized `mutationObserver` and `window.target`.
```javascript
function mutationStart(evt) {
window.target = evt.target;
const opts = {attributes: true, characterData: true, childList: true, subtree: true};
window.mutationObserver.observe(document.documentElement, opts);
}
```
--------------------------------
### Minitest Manual Integration for MagicTest::Support
Source: https://github.com/bullet-train-co/magic_test/wiki/NameError:-undefined-local-variable-or-method-'magic_test'
This snippet demonstrates how to manually include MagicTest::Support in Minitest by adding it to the ApplicationSystemTestCase. This is useful when automatic injection fails and the `magic_test` method is undefined. It requires the MAGIC_TEST environment variable to be present for activation.
```ruby
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
include MagicTest::Support if ENV["MAGIC_TEST"].present?
end
```
--------------------------------
### Install Magic Test with `rails g magic_test:install`
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
Configures a Rails application for Magic Test by creating sample tests, updating configuration, and adding browser support scripts to layouts. It modifies `application_system_test_case.rb` and inserts a partial into `application.html.erb`.
```bash
# Run the installation generator
rails g magic_test:install
# Generator output:
# create test/system/basics_test.rb
# gsub test/application_system_test_case.rb
# insert app/views/layouts/application.html.erb
#
# We just inserted:
# <%= render 'magic_test/support' if Rails.env.test? %>
# before each closing `` tag in all templates in your `layouts` directory.
```
```ruby
# Generated test/system/basics_test.rb
require "application_system_test_case"
class BasicsTest < ApplicationSystemTestCase
test "getting started" do
visit root_path
magic_test
end
end
```
```ruby
# Updated test/application_system_test_case.rb
require "test_helper"
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :selenium,
using: (ENV['MAGIC_TEST'] ? :chrome : :headless_chrome),
screen_size: (ENV['MAGIC_TEST'] ? [800, 1400] : [1400, 1400])
end
```
--------------------------------
### Install Magic Test Gem in Rails Application
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
Adds the Magic Test gem to your Rails application's test dependencies and installs necessary generator files. This setup ensures the gem is available for testing and configures the system test case to work with Magic Test when the `MAGIC_TEST=1` environment variable is set.
```ruby
# Gemfile
group :test do
gem 'magic_test'
end
```
```bash
# Install the gem
bundle install
# Run the installation generator
rails g magic_test:install
# Generate binstubs for easy execution
bundle binstubs magic_test
```
--------------------------------
### Example RSpec System Test with Magic Test
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
An example of an RSpec system test that utilizes the `magic_test` helper. This helper initiates an interactive session for debugging and code generation within the test.
```ruby
require 'rails_helper'
RSpec.describe 'User registration', type: :system do
it 'allows new users to sign up' do
visit root_path
magic_test
end
end
```
```ruby
require 'rails_helper'
RSpec.describe 'Shopping cart', type: :system do
it 'allows adding products to cart' do
product = create(:product, name: 'Magic Keyboard', price: 99.99)
visit products_path
magic_test
# Interactive session opens here
# All magic_test commands (ok, flush, etc.) work identically
end
end
```
--------------------------------
### Run Magic Test with Binstubs
Source: https://github.com/bullet-train-co/magic_test/blob/main/README.md
Executes a system test using Magic Test via generated binstubs. This command can be used for both MiniTest and RSpec.
```bash
bin/magic test test/system/basics_test.rb # for MiniTest
bin/magic spec spec/system/basics_spec.rb # for RSpec
```
--------------------------------
### Run System Tests with Environment Variables
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
Demonstrates how to run system tests using different configurations of the MAGIC_TEST environment variable. This allows for interactive debugging or headless execution in CI/CD pipelines.
```bash
# Interactive development with visible browser
MAGIC_TEST=1 rails test test/system/checkout_test.rb
# Headless CI/CD execution
rails test test/system/checkout_test.rb
# Run all system tests headlessly
rails test:system
```
--------------------------------
### Generate Magic Test Binstubs
Source: https://github.com/bullet-train-co/magic_test/blob/main/README.md
Generates binstubs for the Magic Test gem, allowing you to run Magic Test commands directly. This simplifies the execution of Magic Test commands.
```bash
bundle binstubs magic_test
```
--------------------------------
### Run MiniTest with `bin/magic test`
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
Executes a Rails system test with the `MAGIC_TEST=1` environment variable, launching the visible browser and debugger. This facilitates an interactive three-window workflow. It accepts a path to a specific test file.
```bash
# Run a specific test file
bin/magic test test/system/user_registration_test.rb
# This is equivalent to:
MAGIC_TEST=1 rails test test/system/user_registration_test.rb
# View help
bin/magic --help
# Usage: `bin/magic [option] [path/to/file]`
#
# option = 'test' # will run MiniTest
# option = 'spec' # will run RSpec
```
--------------------------------
### Initialize Magic Test and Event Listeners
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_javascript_helpers.html
This code initializes the Magic Test functionality upon the DOM being ready. It sets up event listeners for 'click', 'keypress', and 'keydown' events to capture user interactions. Dependencies include console logging and custom initialization functions like initializeStorage and initializeMutationObserver.
```javascript
ready(function() {
console.log("🪄 Magic Test activated in the browser!")
initializeStorage();
initializeMutationObserver();
});
```
--------------------------------
### Initialize Mutation Observer (JavaScript)
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_mutation_observer.html
Initializes a MutationObserver to watch for changes in the DOM. It logs mutations and extracts information about the target element, storing it in sessionStorage. Dependencies include the global `MutationObserver` constructor and a `finderForElement` function (not provided).
```javascript
function initializeMutationObserver() {
window.mutationObserver = new MutationObserver(function(mutations) {
console.log("Mutation observed");
if (!window.target) {
console.log("There is no window.target element. Quitting the mutation callback function");
return;
}
var options = "";
var targetClass = window.target.classList[0] ? `.${window.target.classList[0]}` : "";
var text = window.target.innerText ? `', text: '${window.target.innerText}` : "";
var action = `${finderForElement(window.target)}.hover`; // var action = `find('${window.target.localName}${targetClass}${text}').hover`;
var target = "";
var testingOutput = JSON.parse(sessionStorage.getItem("testingOutput"));
testingOutput.push({action: action, target: target, options: options});
sessionStorage.setItem("testingOutput", JSON.stringify(testingOutput));
});
}
```
--------------------------------
### Run Magic Test with Environment Variable
Source: https://github.com/bullet-train-co/magic_test/blob/main/README.md
Manually runs a Rails system test with the MAGIC_TEST environment variable set to 1, enabling interactive testing. This is an alternative to using binstubs.
```bash
MAGIC_TEST=1 rails test test/system/basics_test.rb
```
--------------------------------
### Save Debugger Commands to Test File with `ok`
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
The `ok` command, used within the Pry debugger session initiated by `magic_test`, saves the last executed debugger command or a block of commands to the current location in the test file. It intelligently handles multi-line commands, preserving code structure for loops, conditionals, and blocks.
```ruby
# In the Pry debugger session during magic_test:
[1] pry> click_on "Sign Up"
[2] pry> fill_in "Email", with: "user@example.com"
[3] pry> fill_in "Password", with: "secure_password"
[4] pry> ok
# (writing that to `test/system/user_registration_test.rb`.)
# The test file now contains:
test "user can register for an account" do
visit root_path
magic_test
fill_in "Password", with: "secure_password"
end
# Call ok after each command you want to save:
[5] pry> click_on "Create Account"
[6] pry> ok
[7] pry> assert page.has_content?("Welcome!")
[8] pry> ok
```
--------------------------------
### Render Magic Test Partial in Layouts
Source: https://github.com/bullet-train-co/magic_test/blob/main/README.md
Includes a partial in your application's layout views to enable Magic Test functionality during testing. This partial should be placed before closing tags.
```erb
<%= render 'magic_test/support' if Rails.env.test? %>
```
--------------------------------
### Enable Keystroke Recording with `track_keystrokes`
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
Activates JavaScript keystroke tracking for elements without labels, such as rich text editors. This is useful for testing complex input scenarios where standard `fill_in` commands are insufficient. The test file will include `send_keys` commands.
```ruby
# In the debugger during magic_test:
[1] pry> track_keystrokes
[2] pry> # Now type in a rich text editor in the browser
[3] pry> flush
# The test file includes send_keys commands:
test "user can write a blog post" do
visit new_post_path
magic_test
find('div[contenteditable]').send_keys('This is my blog post content')
end
```
--------------------------------
### JavaScript: Add Keyboard Event Listeners
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_listeners.html
This snippet demonstrates how to add event listeners for keyboard events (keydown, keyup, keypress) in JavaScript. It attaches callback functions to be executed when these keys are pressed or released.
```javascript
document.addEventListener('keydown', function(e){keyDownFunction(e)}, true);
document.addEventListener('keyup', function(e){keyUpFunction(e)}, true);
document.addEventListener('keypress', function(e){keypressFunction(e)});
```
--------------------------------
### Configure Cuprite Driver Headless Option in Ruby
Source: https://github.com/bullet-train-co/magic_test/wiki/Magic-Test-and-Cuprite
This snippet shows the registration of the Cuprite driver with Capybara in a Ruby environment. It configures essential options like `window_size`, `process_timeout`, `inspector`, and dynamically sets the `headless` mode based on environment variables `HEADLESS` and `MAGIC_TEST`. This is crucial for controlling browser visibility during automated testing.
```ruby
require "capybara/cuprite"
Capybara.register_driver(:cuprite) do |app|
Capybara::Cuprite::Driver.new(
app,
**{
window_size: [1200, 800],
# See additional options for Dockerized environment in the respective section of this article
browser_options: {},
# Increase Chrome startup wait time (required for stable CI builds)
process_timeout: 10,
# Enable debugging capabilities
inspector: true,
# Allow running Chrome in a headful mode by setting HEADLESS env
# var to a falsey value
headless: !ENV["HEADLESS"].in?(%w[n 0 no false]) && !ENV["MAGIC_TEST"].in?(%w[y 1 yes true])
}
)
end
```
--------------------------------
### Save Browser Interactions to Test File with `flush`
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
The `flush` command, executed in the Pry debugger, writes all recorded browser interactions (like clicks and form fills) from the current interactive session into the test file as Capybara commands. After flushing, the browser interaction cache is cleared, ready for new recordings.
```ruby
# In the browser during magic_test:
# 1. Click "Sign Up" button
# 2. Fill in "Email" field with "user@example.com"
# 3. Fill in "Password" field with "password123"
# 4. Click "Create Account" button
# Then in the debugger:
[1] pry> flush
# javascript recorded on the front-end looks like this:
# [{"action"=>"click_on", "target"=>"'Sign Up'", "options"=>""},
# {"action"=>"fill_in", "target"=>"'Email'", "options"=>", with: 'user@example.com'"},
# {"action"=>"fill_in", "target"=>"'Password'", "options"=>", with: 'password123'"},
# {"action"=>"click_on", "target"=>"'Create Account'", "options"=>""}]
#
# (writing that to `test/system/user_registration_test.rb`.)
# The test file now contains:
test "user can register for an account" do
visit root_path
magic_test
click_on 'Sign Up'
fill_in 'Email', with: 'user@example.com'
fill_in 'Password', with: 'password123'
click_on 'Create Account'
end
```
--------------------------------
### Run RSpec with `bin/magic spec`
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
Executes an RSpec system test with Magic Test enabled, providing the same interactive development experience for RSpec users. It allows running specific spec files and is equivalent to setting the `MAGIC_TEST=1` environment variable.
```bash
# Run a specific spec file
bin/magic spec spec/system/user_registration_spec.rb
# This is equivalent to:
MAGIC_TEST=1 rspec spec/system/user_registration_spec.rb
```
--------------------------------
### Render dynamic content with ERB in HTML
Source: https://github.com/bullet-train-co/magic_test/blob/main/test/support/layouts/application.txt
This snippet shows how to embed dynamic content within an HTML page using ERB (Embedded Ruby) templating. The `<%= yield %>` tag is a common convention in Ruby on Rails applications to insert the content of the current view into a layout file. No external dependencies are required beyond a Ruby environment capable of processing ERB.
```html
Magic Test | Application fake layout
<%= yield %>
```
--------------------------------
### Integrate Layout for Browser Tracking
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
Renders a JavaScript partial in the layout's head section to enable browser interaction tracking. This partial only renders in the test environment when MAGIC_TEST is present, ensuring no impact on production.
```erb
My Application
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag "application" %>
<%= render 'magic_test/support' if Rails.env.test? %>
<%= yield %>
```
--------------------------------
### Initiate Interactive Testing with `magic_test`
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
The `magic_test` function pauses test execution and launches an interactive Pry debugger session. This allows developers to write Capybara commands manually or interact with the application via the browser. All actions performed during this session are tracked and can be saved to the test file, streamlining the test creation process.
```ruby
require "application_system_test_case"
class UserRegistrationTest < ApplicationSystemTestCase
test "user can register for an account" do
visit root_path
# Pauses here and opens interactive debugger
magic_test
end
end
```
```bash
# Run with Magic Test enabled
MAGIC_TEST=1 rails test test/system/user_registration_test.rb
# Or using the binstub
bin/magic test test/system/user_registration_test.rb
```
--------------------------------
### Configure Environment-Based Browser Mode
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
Configures the browser driver to use either a visible Chrome instance for interactive development or headless Chrome for CI/CD execution. This is controlled by the MAGIC_TEST environment variable.
```ruby
require "test_helper"
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :selenium,
using: (ENV['MAGIC_TEST'] ? :chrome : :headless_chrome),
screen_size: (ENV['MAGIC_TEST'] ? [800, 1400] : [1400, 1400])
end
```
--------------------------------
### JavaScript: Add Mouse and Mutation Event Listeners
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_listeners.html
This snippet shows how to add event listeners for mouseover and click events in JavaScript. It also includes listeners for mutation detection, which can be triggered by mouseover events.
```javascript
document.addEventListener('mouseover', function(evt){mutationStart(evt)}, true);
document.addEventListener('mouseover', function(){mutationEnd()}, false);
document.addEventListener('click', function(event){clickFunction(event)});
```
--------------------------------
### Handle Keydown Events for Dynamic Input Capture
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_javascript_helpers.html
This function captures 'keydown' events to record user input, especially for elements without labels. It constructs an action like `find('tag_name').send_keys(...)` and updates session storage. It handles special characters and intelligently merges consecutive key presses into a single action. It also includes logic to reset the action if the previous key pressed was 'enter' to correctly handle UI elements like mentions.
```javascript
function keyDownFunction(evt){
if (evt.target.labels) {
return;
}
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = capybaraFromCharCode(charCode);
var letter = evt.key == "'" ? "\\\'" : evt.key;
var tagName = evt.target.tagName.toLowerCase();
var action = finderForElement(evt.target) + "." // `find('${tagName}').`
var target = ""
if (charStr) {
target = `send_keys(${charStr})`;
} else {
target = `send_keys('${letter}')`;
}
var options = "";
var testingOutput = JSON.parse(sessionStorage.getItem("testingOutput"));
var lastAction = testingOutput[testingOutput.length - 1]
// If the last key pressed was enter, always start a new action (otherwise with trix mentions, it happens too fast and we don't actually select the mentioned user correctly.)
if (lastAction && lastAction.target.substr(lastAction.target.length - 7 , 6) == ":enter") {
lastAction = null;
}
if (lastAction && lastAction.action == action && lastAction.target.substr(0,9) == 'send_keys') {
if (charStr) {
lastAction.target = lastAction.target.substr(0, lastAction.target.length - 1) + ', ' + charStr + ')'
} else {
if (lastAction.target.substr(lastAction.target.length - 2, 1) == "'") {
lastAction.target = lastAction.target.substr(0, lastAction.target.length - 2) + letter + '\'' + ')'
} else {
lastAction.target = lastAction.target.substr(0, lastAction.target.length - 1) + ', \'' + letter + '\'' + ')'
}
}
} else {
testingOutput.push({action: action, target: target, options: options});
}
sessionStorage.setItem("testingOutput", JSON.stringify(testingOutput));
}
```
--------------------------------
### Generate Assertions with `assert_selected_exists`
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
Creates assertions by selecting text in the browser, triggered by keyboard shortcuts or context menus. Special characters in selected text are escaped. It retrieves selected text using `page.evaluate_script` and `window.selectedText()`.
```ruby
# In the browser during magic_test:
# 1. Complete a user registration
# 2. Highlight the text "Welcome to the application!"
# 3. Press Ctrl+Shift+A (or right-click and confirm)
# The test file is automatically updated:
test "user can register for an account" do
visit root_path
magic_test
click_on 'Sign Up'
fill_in 'Email', with: 'user@example.com'
fill_in 'Password', with: 'password123'
click_on 'Create Account'
assert(page.has_content?('Welcome to the application!'))
end
```
--------------------------------
### Handle Click Events for User Interaction
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_javascript_helpers.html
This JavaScript function captures 'click' events on various HTML elements (BUTTON, A, INPUT[type=submit], INPUT). It determines the action (e.g., 'click_on') and target based on the element's tag name and attributes. The interaction is then stored in session storage. It includes logic to handle input elements and extract relevant information for test automation.
```javascript
function clickFunction(event) {
var element = event.target
var tagName = element.tagName
var action = ""
var target = ""
var options = ""
if (tagName == "BUTTON" || tagName == "A" || (tagName == "INPUT" && element.type == 'submit')) {
action = "click_on"
target = element.value || element.text
if (!target) {
return;
}
target = "'" + target.trim().replace("'", "\\\'") + "'"
} else if (tagName == "INPUT") {
let ignoreType = new Array('text', 'password', 'date', 'email', 'month', 'number', 'search')
if (ignoreType.includes(element.type)) {
return;
}
var path = getPathTo(element)
action = `find(:xpath, '${path}').click`
} else {
return;
}
var testingOutput = JSON.parse(sessionStorage.getItem("testingOutput"));
testingOutput.push({action: action, target: target, options: options});
sessionStorage.setItem("testingOutput", JSON.stringify(testingOutput));
};
```
--------------------------------
### Handle Keypress Events for Form Input
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_javascript_helpers.html
This function processes 'keypress' events, primarily for input fields, to capture text being typed. It extracts the character code, determines the corresponding character, and constructs an action to 'fill_in' a target (identified by its label). It updates the last recorded action in session storage if it's the same input, otherwise, it adds a new entry. Dependencies include session storage and a utility function `capybaraFromCharCode` (not provided).
```javascript
function keypressFunction(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
if (!evt.target.labels) {
return;
}
var label = evt.target.labels[0].textContent;
var text = (evt.target.value + charStr).trim().replace("'", "\\\'");
var action = "fill_in";
var target = evt.target.labels[0].textContent;
var options = ", with: '" + text + "'";
var testingOutput = JSON.parse(sessionStorage.getItem("testingOutput"));
var lastAction = testingOutput[testingOutput.length - 1]
if (lastAction && lastAction.action == action && lastAction.target == "'" + target + "'") {
lastAction.options = options;
} else {
testingOutput.push({action: action, target: "'" + target + "'", options: options});
}
sessionStorage.setItem("testingOutput", JSON.stringify(testingOutput));
}
```
--------------------------------
### Generate Element Path (JavaScript)
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_finders.html
The `getPathTo` function recursively constructs a path to a given HTML element, similar to an XPath. It identifies the element by its tag name and its index among its siblings of the same tag name. It handles the 'HTML' and 'BODY' elements as special cases.
```javascript
function getPathTo(element) {
if (element.tagName === 'HTML') {
return '/HTML[1]';
}
if (element === document.body) {
return '/HTML[1]/BODY[1]';
}
var ix = 0;
var siblings = element.parentNode.childNodes;
for (var i = 0; i < siblings.length; i++) {
var sibling = siblings[i];
if (sibling === element) {
return getPathTo(element.parentNode) + '/' + element.tagName + '[' + (ix + 1) + ']';
}
if (sibling.nodeType === 1 && sibling.tagName === element.tagName) {
ix++;
}
}
}
```
--------------------------------
### Map Key Up Codes to Magic Test Identifiers (JavaScript)
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_key_codes.html
The `capybaraKeyUpFromCharCode` function maps specific character codes to their Magic Test key identifiers when a key is released. This function is more limited than `capybaraFromCharCode` and primarily focuses on modifier and command keys. It returns undefined for unmapped codes.
```javascript
function capybaraKeyUpFromCharCode(charCode) {
codes = {
16: ':shift',
17: ':control',
18: ':alt',
91: ':command'
};
return codes[charCode];
}
```
--------------------------------
### Map Key Codes to Magic Test Identifiers (JavaScript)
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_key_codes.html
The `capybaraFromCharCode` function maps a given character code to its corresponding Magic Test key identifier. This is useful for simulating key presses in automated tests. It handles a wide range of special keys including control, function, and navigation keys. It returns undefined if the character code is not found in the mapping.
```javascript
function capybaraFromCharCode(charCode) {
codes = {
8: ':backspace',
9: ':tab',
13: ':enter',
16: ':shift',
17: ':control',
18: ':alt',
19: ':pause',
27: ':escape',
33: ':page_up',
34: ':page_down',
35: ':end',
36: ':home',
37: ':left',
38: ':up',
39: ':right',
40: ':down',
45: ':insert',
46: ':delete',
91: ':command',
112: ':f1',
113: ':f2',
114: ':f3',
115: ':f4',
116: ':f5',
117: ':f6',
118: ':f7',
119: ':f8',
120: ':f9',
121: ':f10',
122: ':f11',
123: ':f12'
};
return codes[charCode];
}
```
--------------------------------
### Handle Keyup Events for Input Completion
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_javascript_helpers.html
This function processes 'keyup' events to finalize input actions, particularly when special characters or specific key sequences are involved. It aims to capture the full input string after a key is released and append it to the 'send_keys' action in session storage. It handles cases where characters might not be directly translatable by `capybaraKeyUpFromCharCode` (not provided).
```javascript
function keyUpFunction(evt){
if (evt.target.labels) {
return;
}
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = capybaraKeyUpFromCharCode(charCode);
if (!charStr) {
return;
}
var letter = String.fromCharCode(charCode);
var tagName = evt.target.tagName.toLowerCase();
var action = `find('${tagName}').`;
var target = ""
if (charStr) {
target = `send_keys(${charStr})`;
} else {
target = `send_keys('${letter}')`;
}
var options = "";
var testingOutput = JSON.parse(sessionStorage.getItem("testingOutput"));
var lastAction = testingOutput[testingOutput.length - 1]
if (lastAction && lastAction.action == action && lastAction.target.substr(0,9) == 'send_keys') {
if (charStr) {
lastAction.target = lastAction.target.substr(0, lastAction.target.length - 1) + ', ' + charStr + '' + ')'
} else {
lastAction.target = lastAction.target.substr(0, lastAction.target.length - 1) + ', \'' + letter + '\'' + ')'
}
} else {
testingOutput.push({action: action, target: target, options: options});
}
sessionStorage.setItem("testingOutput", JSON.stringify(testingOutput));
}
```
--------------------------------
### Clear Browser Cache with `empty_cache`
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
Clears the browser's session storage where Magic Test records user interactions, resetting the interaction history. This is automatically called after `flush` to prevent duplicate recording. Raises `Capybara::NotSupportedByDriverError` in headless mode.
```ruby
# In the debugger during magic_test:
[1] pry> click_on "Dashboard"
[2] pry> flush
# Actions are saved to test file
[3] pry> empty_cache
# Clears the browser's interaction cache
[4] pry> click_on "Settings"
[5] pry> flush
# Only the "Settings" click is saved, not "Dashboard"
```
--------------------------------
### RSpec Integration for Magic Test
Source: https://context7.com/bullet-train-co/magic_test/llms.txt
Automatically includes MagicTest::Support in RSpec system type tests when the MAGIC_TEST environment variable is present. This allows Magic Test functionality to be used within RSpec system specs.
```ruby
module MagicTest
class Engine < Rails::Engine
config.after_initialize do
if ENV["MAGIC_TEST"].present?
if defined? RSpec
RSpec.configure do |config|
config.include MagicTest::Support, type: :system
end
end
end
end
end
end
```
--------------------------------
### Rails Default Error Page CSS
Source: https://github.com/bullet-train-co/magic_test/blob/main/test/dummy/public/422.html
This CSS styles the default error page in a Rails application, providing a visually distinct layout for error messages. It targets elements like the dialog box, headings, and paragraphs to present error information clearly. No external dependencies are required beyond standard HTML structure.
```css
.rails-default-error-page { background-color: #EFEFEF; color: #2E2F30; text-align: center; font-family: arial, sans-serif; margin: 0; }
.rails-default-error-page div.dialog { width: 95%; max-width: 33em; margin: 4em auto 0; }
.rails-default-error-page div.dialog > div { border: 1px solid #CCC; border-right-color: #999; border-left-color: #999; border-bottom-color: #BBB; border-top: #B00100 solid 4px; border-top-left-radius: 9px; border-top-right-radius: 9px; background-color: white; padding: 7px 12% 0; box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17); }
.rails-default-error-page h1 { font-size: 100%; color: #730E15; line-height: 1.5em; }
.rails-default-error-page div.dialog > p { margin: 0 0 1em; padding: 1em; background-color: #F7F7F7; border: 1px solid #CCC; border-right-color: #999; border-left-color: #999; border-bottom-color: #999; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-top-color: #DADADA; color: #666; box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17); }
```
--------------------------------
### End Mutation Observation (JavaScript)
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_mutation_observer.html
Stops the MutationObserver from observing any further DOM changes. This function disconnects the observer, preventing it from triggering its callback. It requires a previously initialized `mutationObserver`.
```javascript
function mutationEnd () {
window.mutationObserver.disconnect();
}
```
--------------------------------
### Find Unique Element Selector (JavaScript)
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_finders.html
The `finderForElement` function attempts to generate a unique selector for a given HTML element. It prioritizes simpler selectors like tag name, tag name with classes, and tag name with classes and text content. If these fail, it falls back to using the generated path (XPath) for the element.
```javascript
function finderForElement(element) {
// Try to find just using the element tagName
var tagName = element.tagName.toLowerCase();
if (document.querySelectorAll(tagName).length === 1) {
return `find('${tagName}')`;
}
// Try adding in the classes of the element
var classList = [].slice.apply(element.classList);
var classString = classList.length ? '.' + classList.join('.') : '';
if (classList.length && document.querySelectorAll(tagName + classString).length === 1) {
return `find('${tagName}${classString}')`;
}
// Try adding in the text of the element
var text = element.textContent.trim();
var targets = Array.from(document.querySelectorAll(`${tagName}${classString}`))
.filter(visibleFilter)
.filter((el) => el.textContent.includes(text));
if (text && targets.length === 1) {
return `find('${tagName}${classString}', text: '${text}')`;
}
// use the xpath to the element
return `find(:xpath, '${getPathTo(element)}')`;
}
```
--------------------------------
### Filter Visible Elements (JavaScript)
Source: https://github.com/bullet-train-co/magic_test/blob/main/app/views/magic_test/_finders.html
The `visibleFilter` function checks if a target HTML element is visible. It considers elements with `display: none`, `visibility: hidden`, or the `hidden` attribute as not visible. This is useful for filtering elements that might exist in the DOM but are not rendered.
```javascript
function visibleFilter(target) {
var computedStyle = window.getComputedStyle(target);
return !(computedStyle.display === 'none' || computedStyle.visibility === 'hidden' || target.hidden);
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.