### Run Minitest Rails Installation Generator Source: https://context7.com/minitest/minitest-rails/llms.txt Command to run the Rails generator provided by the minitest-rails gem. This command sets up the necessary files and configurations for Minitest within your Rails project. ```bash # Run the installation generator rails generate minitest:install ``` -------------------------------- ### Install Minitest Rails Gem Source: https://context7.com/minitest/minitest-rails/llms.txt Instructions to add the minitest-rails gem to your Rails application's Gemfile, matching the version to your Rails version for compatibility. This is the first step in integrating Minitest with Rails. ```ruby # Add to Gemfile - match the version to your Rails version gem "minitest-rails", "~> 8.1.0" # For Rails 8.1 gem "minitest-rails", "~> 8.0.0" # For Rails 8.0 gem "minitest-rails", "~> 7.2.0" # For Rails 7.2 ``` -------------------------------- ### Generate Rails Models and Controllers with Minitest Options Source: https://context7.com/minitest/minitest-rails/llms.txt Command-line examples for generating Rails models and controllers using the `rails generate` command, demonstrating options to control Minitest behavior like using spec DSL or skipping fixtures. ```bash # Generate model with spec DSL (default) rails generate model User name:string email:string # Generate model without spec DSL rails generate model User name:string email:string --no-spec # Generate model without fixture rails generate model User name:string email:string --skip-fixture # Generate controller rails generate controller Articles index show # Generate scaffold rails generate scaffold Article title:string body:text ``` -------------------------------- ### Model Testing with Minitest Spec DSL in Rails Source: https://context7.com/minitest/minitest-rails/llms.txt Example of writing model tests using the Minitest::Spec DSL (describe/it blocks) in a Rails application. It demonstrates testing model validations and creation. ```ruby # test/models/user_test.rb require "test_helper" describe User do let(:user) { users(:one) } it "must be valid with valid attributes" do value(user).must_be :valid? end it "requires an email" do user.email = nil value(user).wont_be :valid? end it "creates a user" do value { User.create(email: "test@example.com", password: "secret") } .must_differ "User.count" end it "does not create duplicate emails" do value { User.create(email: user.email, password: "secret") } .wont_differ "User.count" end end ``` -------------------------------- ### Controller Testing with Minitest Spec DSL in Rails Source: https://context7.com/minitest/minitest-rails/llms.txt Example of controller tests using the Minitest::Spec DSL in Rails, leveraging integration test features. It covers testing actions like index, new, create, show, edit, update, and destroy. ```ruby # test/controllers/articles_controller_test.rb require "test_helper" describe ArticlesController do let(:article) { articles(:one) } it "should get index" do get articles_url must_respond_with :success end it "should get new" do get new_article_url must_respond_with :success end it "should create article" do assert_difference("Article.count") do post articles_url, params: { article: { title: "New", body: "Content" } } end must_redirect_to article_url(Article.last) end it "should show article" do get article_url(article) must_respond_with :success end it "should get edit" do get edit_article_url(article) must_respond_with :success end it "should update article" do patch article_url(article), params: { article: { title: "Updated" } } must_redirect_to article_url(article) end it "should destroy article" do assert_difference("Article.count", -1) do delete article_url(article) end must_redirect_to articles_url end end ``` -------------------------------- ### Model Testing with Traditional Assertions in Rails Source: https://context7.com/minitest/minitest-rails/llms.txt Example of writing model tests using traditional Minitest assertion methods within a Rails application. It shows how to test model validity and the effect of creating records. ```ruby # test/models/article_test.rb require "test_helper" class ArticleTest < ActiveSupport::TestCase def test_should_be_valid article = Article.new(title: "Test", body: "Content") assert article.valid? end def test_should_create_article assert_difference "Article.count" do Article.create(title: "New Article", body: "Body content") end end def test_should_not_change_count_with_invalid_data refute_difference "Article.count" do Article.create(title: nil) # Invalid - title required end end end ``` -------------------------------- ### Expectations: must_change vs. must_differ in Minitest-Rails Source: https://github.com/minitest/minitest-rails/blob/master/UPDATING.md Explains the change in the `must_change` expectation's signature due to its reliance on Rails' `assert_changes` assertion (Rails 5.1+). The `must_differ` expectation is now used for the `assert_difference` assertion. ```ruby # Previously used assert_difference, now uses assert_changes must_change # For assert_difference must_differ ``` -------------------------------- ### Spec DSL: Correct Constant Referencing in Minitest-Rails Source: https://github.com/minitest/minitest-rails/blob/master/UPDATING.md Demonstrates the correct way to reference constants within the `describe` block in Minitest-Rails. The `describe` block should receive the actual constant, not its string representation, to function correctly. An optional second argument can be provided to specify the test class if a string is used. ```ruby describe WidgetsController do end ``` ```ruby describe "WidgetsController", :controller do end ``` -------------------------------- ### Declare Spec Type with Symbols in Minitest Rails Source: https://context7.com/minitest/minitest-rails/llms.txt This snippet demonstrates how to explicitly declare the type of a test specification using symbols in Minitest Rails. It shows examples for various Rails components like models, integration tests, mailers, jobs, channels, helpers, views, generators, connections, and system tests. ```ruby # Explicit spec type declaration using symbols describe "User Features", :model do # Uses ActiveSupport::TestCase end describe "Home Page", :integration do # Uses ActionDispatch::IntegrationTest end describe "Welcome Email", :mailer do # Uses ActionMailer::TestCase end describe "Background Tasks", :job do # Uses ActiveJob::TestCase end describe "Live Updates", :channel do # Uses ActionCable::Channel::TestCase end describe "View Helpers", :helper do # Uses ActionView::TestCase end describe "Template Rendering", :view do # Uses ActionView::TestCase end describe "Model Generator", :generator do # Uses Rails::Generators::TestCase end describe "WebSocket Auth", :connection do # Uses ActionCable::Connection::TestCase end describe "Browser Tests", :system do # Uses ActionDispatch::SystemTestCase end ``` -------------------------------- ### Configure Minitest Rails Test Helper Source: https://context7.com/minitest/minitest-rails/llms.txt Configuration for the test_helper.rb file to set up the testing environment for Minitest in Rails. It includes requiring necessary files, enabling parallel testing, and setting up fixtures. ```ruby # test/test_helper.rb ENV["RAILS_ENV"] ||= "test" # Set MT_NO_EXPECTATIONS to disable expectations on Object # ENV["MT_NO_EXPECTATIONS"] = "true" require_relative "../config/environment" require "rails/test_help" require "minitest/rails" module ActiveSupport class TestCase # Run tests in parallel with specified workers parallelize(workers: :number_of_processors) # Setup all fixtures in test/fixtures/*.yml fixtures :all # Add more helper methods to be used by all tests here... end end ``` -------------------------------- ### Test ActionCable Broadcasts with Minitest Source: https://context7.com/minitest/minitest-rails/llms.txt This snippet demonstrates how to test ActionCable WebSocket broadcasts using Minitest. It covers asserting the number of broadcasts, broadcasts within a block, and verifying no broadcasts occur. It also shows how to test specific broadcast data and stream subscriptions. ```ruby # test/channels/chat_channel_test.rb require "test_helper" class ChatChannelTest < ActionCable::Channel::TestCase def test_broadcasts_count assert_broadcasts 'messages', 0 ActionCable.server.broadcast 'messages', { text: 'hello' } assert_broadcasts 'messages', 1 ActionCable.server.broadcast 'messages', { text: 'world' } assert_broadcasts 'messages', 2 end def test_broadcasts_in_block assert_broadcasts('messages', 1) do ActionCable.server.broadcast 'messages', { text: 'hello' } end assert_broadcasts('messages', 2) do ActionCable.server.broadcast 'messages', { text: 'hi' } ActionCable.server.broadcast 'messages', { text: 'how are you?' } end end def test_no_broadcasts refute_broadcasts 'messages' ActionCable.server.broadcast 'messages', { text: 'hi' } assert_broadcasts 'messages', 1 end def test_broadcast_on_specific_data assert_broadcast_on('messages', text: 'hello') do ActionCable.server.broadcast 'messages', text: 'hello' end end def test_stream_subscriptions subscribe assert_has_stream 'messages' end def test_stream_for_model subscribe id: 42 assert_has_stream_for User.find(42) end def test_no_streams subscribe refute_streams # or assert_no_streams end end # Using spec expectations describe ChatChannel, :channel do it "has broadcasts" do must_have_broadcasts 'messages', 0 ActionCable.server.broadcast 'messages', { text: 'hello' } must_have_broadcasts 'messages', 1 end it "broadcasts in block" do must_have_broadcasts('messages', 1) do ActionCable.server.broadcast 'messages', { text: 'hello' } end end it "has no broadcasts initially" do wont_have_broadcasts 'messages' end it "broadcasts specific data" do must_broadcast_on('messages', text: 'hello') do ActionCable.server.broadcast 'messages', text: 'hello' end end it "subscribes to stream" do subscribe must_have_streams 'messages' end it "subscribes to model stream" do subscribe id: 42 must_have_stream_for User.find(42) end end ``` -------------------------------- ### Perform System Tests with Minitest and Spec DSL Source: https://context7.com/minitest/minitest-rails/llms.txt System tests for browser-based integration testing of articles. This includes visiting the index page, creating, updating, and destroying articles, with assertions on page content and selectors. ```ruby # test/system/articles_test.rb require "application_system_test_case" describe "Articles", :system do let(:article) { articles(:one) } it "visits the index" do visit articles_url assert_selector "h1", text: "Articles" end it "creates a new article" do visit articles_url click_on "New Article" fill_in "Title", with: "Test Article" fill_in "Body", with: "This is the article body" click_on "Create Article" assert_text "Article was successfully created" end it "updates an article" do visit article_url(article) click_on "Edit" fill_in "Title", with: "Updated Title" click_on "Update Article" assert_text "Article was successfully updated" end it "destroys an article" do visit article_url(article) click_on "Destroy", match: :first assert_text "Article was successfully destroyed" end end ``` -------------------------------- ### Test Action Cable Connections with Minitest Source: https://context7.com/minitest/minitest-rails/llms.txt Tests for Action Cable connections, verifying successful connections with proper cookies and rejecting connections without them. Uses both traditional test methods and spec expectations. ```ruby require "test_helper" class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase def test_connects_with_proper_cookie # Simulate the connection request with a cookie cookies["user_id"] = users(:john).id connect # Assert the connection identifier matches the fixture assert_equal users(:john).id, connection.user.id end def test_rejects_connection_without_proper_cookie assert_reject_connection { connect } end end # Using spec expectations describe "Application Connections", :connection do it "connects with proper cookie" do cookies["user_id"] = users(:john).id connect value(connection.user.id).must_equal users(:john).id end it "rejects connection without proper cookie" do must_reject_connection { connect } end end ``` -------------------------------- ### Configure Rails Generators for Minitest Source: https://github.com/minitest/minitest-rails/blob/master/README.md Demonstrates how to set default test framework configurations for Minitest within the `config/application.rb` file. This allows you to disable spec DSL or fixtures globally. ```ruby config.generators do |g| g.test_framework :minitest, spec: false, fixture: false end ``` -------------------------------- ### Routing Assertions in Rails (Minitest) Source: https://context7.com/minitest/minitest-rails/llms.txt Tests Rails routing configurations to ensure routes are correctly generated and recognized. Assertions like `assert_generates`, `assert_recognizes`, and `assert_routing` verify that URLs map to the correct controller actions and parameters, and vice versa. Supports testing with different HTTP methods. ```ruby # test/controllers/routing_test.rb require "test_helper" class RoutingTest < ActionDispatch::IntegrationTest def test_generates_correct_path # Assert default action route assert_generates "/items", controller: "items", action: "index" # Test route with action assert_generates "/items/list", controller: "items", action: "list" # Test route with parameter assert_generates "/items/list/1", { controller: "items", action: "list", id: "1" } # Test custom route assert_generates "changesets/12", { controller: 'scm', action: 'show_diff', revision: "12" } end def test_recognizes_routes # Check the default route assert_recognizes({ controller: 'items', action: 'index' }, 'items') # Test a specific action assert_recognizes({ controller: 'items', action: 'list' }, 'items/list') # Test an action with a parameter assert_recognizes({ controller: 'items', action: 'destroy', id: '1' }, 'items/destroy/1') # Test POST routing assert_recognizes({ controller: 'items', action: 'create' }, { path: 'items', method: :post }) end def test_bidirectional_routing # Assert route works both ways assert_routing '/home', controller: 'home', action: 'index' assert_routing '/entries/show/23', controller: 'entries', action: 'show', id: "23" # Test route with HTTP method assert_routing({ method: 'put', path: '/product/321' }, { controller: "product", action: "update", id: "321" }) end end ``` -------------------------------- ### Generate and Recognize Routes with Minitest Source: https://context7.com/minitest/minitest-rails/llms.txt Tests route generation and recognition using Minitest's integration tests. It verifies that specific controller actions map to correct URL paths and that given paths are routed to the expected controller actions. ```ruby describe "Routing", :integration do it "generates routes correctly" do value({ controller: "items", action: "index" }).must_route_to "/items" end it "recognizes routes correctly" do value('items').must_route_from({ controller: 'items', action: 'index' }) value('items/list').must_route_from({ controller: 'items', action: 'list' }) end it "routes bidirectionally" do value({ controller: 'home', action: 'index' }).must_route_for '/home' end end ``` -------------------------------- ### Test ActiveJob Enqueueing and Execution with Minitest Source: https://context7.com/minitest/minitest-rails/llms.txt Provides methods for testing ActiveJob background jobs. It allows assertions on the number of enqueued jobs, specific job arguments, and whether jobs were performed. ```ruby # test/jobs/hello_job_test.rb require "test_helper" class HelloJobTest < ActiveJob::TestCase def test_enqueued_jobs_count assert_enqueued_jobs 0 HelloJob.perform_later('david') assert_enqueued_jobs 1 HelloJob.perform_later('abdelkader') assert_enqueued_jobs 2 end def test_enqueue_in_block assert_enqueued_jobs 1 do HelloJob.perform_later('cristian') end assert_enqueued_jobs 2 do HelloJob.perform_later('aaron') HelloJob.perform_later('rafael') end end def test_no_jobs_enqueued refute_enqueued_jobs HelloJob.perform_later('jeremy') assert_enqueued_jobs 1 end def test_enqueued_with_specific_args assert_enqueued_with(job: MyJob, args: [1, 2, 3], queue: 'low') do MyJob.perform_later(1, 2, 3) end end def test_performed_jobs assert_performed_jobs 1 do HelloJob.perform_later('robin') end refute_performed_jobs do # No job should be performed from this block end end def test_performed_with_specific_args assert_performed_with(job: MyJob, args: [1, 2, 3], queue: 'high') do MyJob.perform_later(1, 2, 3) end end end ``` ```ruby # Using spec expectations describe HelloJob do it "enqueues jobs" do must_enqueue_jobs 1 do HelloJob.perform_later('cristian') end end it "has no enqueued jobs initially" do wont_enqueue_jobs HelloJob.perform_later('jeremy') must_enqueue_jobs 1 end it "enqueues with specific arguments" do must_enqueue_with(job: MyJob, args: [1, 2, 3], queue: 'low') do MyJob.perform_later(1, 2, 3) end end it "performs jobs" do must_perform_jobs 2 do HelloJob.perform_later('carlos') HelloJob.perform_later('sean') end end end ``` -------------------------------- ### Configure minitest-rails Gem Version for Rails Source: https://github.com/minitest/minitest-rails/blob/master/README.md Specifies how to add the minitest-rails gem to your Gemfile based on your Rails version. This ensures compatibility and proper integration with your Rails project. ```ruby gem "minitest-rails", "~> 8.1.0" ``` ```ruby gem "minitest-rails", "~> 8.0.0" ``` ```ruby gem "minitest-rails", "~> 7.2.0" ``` ```ruby gem "minitest-rails", "~> 7.1.0" ``` ```ruby gem "minitest-rails", "~> 7.0.0" ``` ```ruby gem "minitest-rails", "~> 6.1.0" ``` ```ruby gem "minitest-rails", "~> 6.0.0" ``` -------------------------------- ### DOM Selection and HTML Assertions in Rails (Minitest) Source: https://context7.com/minitest/minitest-rails/llms.txt Tests the structure and content of HTML responses using CSS selectors. Assertions like `assert_select` and `must_select` verify the presence, count, and attributes of HTML elements. Useful for checking page titles, form fields, and nested structures. ```ruby # test/controllers/home_controller_test.rb require "test_helper" class HomeControllerTest < ActionDispatch::IntegrationTest def test_page_structure get root_url # At least one form element assert_select "form" # Form element includes four input fields assert_select "form input", 4 # Page title is "Welcome" assert_select "title", "Welcome" # Page title with count validation assert_select "title", { count: 1, text: "Welcome" }, "Wrong title or more than one title element" # Page contains no error messages assert_select ".error", false, "Page must contain no errors" # Test nested content assert_select "body div.header ul.menu" # All input fields in the form have a name assert_select "form input" do |elements| assert_select elements, "[name=?]", /.+/ # Not empty end end def test_ordered_lists get items_url # If response contains two ordered lists with four items each assert_select "ol" do |elements| elements.each do |element| assert_select element, "li", 4 end end end end # Using spec expectations describe HomeController do it "has proper page structure" do get root_url must_select "form" must_select "title", "Welcome" must_select "form input", 4 end end ``` -------------------------------- ### Test Changes and Differences with ActiveSupport Assertions Source: https://context7.com/minitest/minitest-rails/llms.txt Utilizes ActiveSupport::TestCase to assert whether specific expressions change or remain unchanged during block execution. It covers scenarios like status changes, article count differences, and verifying no changes occur. ```ruby # test/models/status_test.rb require "test_helper" class StatusTest < ActiveSupport::TestCase def test_changes_status assert_changes "Status.all_good?" do post :create, params: { status: { ok: false } } end end def test_no_changes_to_status refute_changes "Status.all_good?" do post :create, params: { status: { ok: true } } end end def test_difference_in_count assert_difference "Article.count" do Article.create(title: "New Article", body: "Content") end assert_difference "Article.count", 3 do 3.times { Article.create(title: "Article", body: "Body") } end end def test_no_difference refute_difference "Article.count" do Article.create(title: nil) # Invalid - won't save end end end ``` ```ruby # Using spec expectations describe "Status Changes" do it "changes user count" do value { User.create(email: "test@example.com", password: "valid") } \ .must_change "User.count" end it "changes count by specific amount" do value { 3.times { User.create(email: "#{rand}@example.com", password: "valid") } } \ .must_differ "User.count", 3 end it "does not change count with invalid data" do value { User.new }.wont_differ "User.count" end it "changes from one value to another" do value { User.create(email: "new@example.com", password: "valid") } \ .must_change "User.count", from: 5, to: 6 end end ``` -------------------------------- ### DOM Equality Assertions in Rails (Minitest) Source: https://context7.com/minitest/minitest-rails/llms.txt Compares generated HTML strings against expected HTML for exact equivalence. Assertions like `assert_dom_equal` and `must_dom_equal` are used to ensure that helper methods or view components produce the correct HTML output. Useful for testing link generation and other HTML-producing helpers. ```ruby # test/helpers/link_helper_test.rb require "test_helper" class LinkHelperTest < ActionView::TestCase def test_link_generation expected = 'Apples' assert_dom_equal expected, link_to("Apples", "http://www.example.com") end def test_different_links orange_link = 'Oranges' refute_dom_equal orange_link, link_to("Apples", "http://www.example.com") end end # Using spec expectations describe "LinkHelper" do it "generates correct link HTML" do apple_link = 'Apples' value(link_to("Apples", "http://www.example.com")).must_dom_equal apple_link end it "generates different HTML for different text" do orange_link = 'Oranges' link_to("Apples", "http://www.example.com").wont_dom_equal orange_link end end ``` -------------------------------- ### Automatic Spec Type Registration in Minitest Rails Source: https://context7.com/minitest/minitest-rails/llms.txt Demonstrates how Minitest automatically detects and registers the appropriate test case class based on the described object, such as ActiveRecord models, controllers, mailers, jobs, channels, and generators. ```ruby # Automatic spec type detection based on class inheritance describe User do # Inherits from ActiveSupport::TestCase for ActiveRecord models end describe ArticlesController do # Inherits from ActionDispatch::IntegrationTest for controllers end describe ContactMailer do # Inherits from ActionMailer::TestCase for mailers end describe HelloJob do # Inherits from ActiveJob::TestCase for jobs end describe ChatChannel do # Inherits from ActionCable::Channel::TestCase for channels end describe MyGenerator do # Inherits from Rails::Generators::TestCase for generators end ``` -------------------------------- ### Test Mailer Email Assertions with Minitest Source: https://context7.com/minitest/minitest-rails/llms.txt This snippet demonstrates how to test mailers in Rails using Minitest. It covers asserting the number of emails sent, emails sent within a block, and verifying that no emails are sent. It also shows how to test enqueued emails and specific mailer methods with arguments. ```ruby require "test_helper" class ContactMailerTest < ActionMailer::TestCase def test_email_count assert_emails 0 ContactMailer.welcome.deliver_now assert_emails 1 ContactMailer.welcome.deliver_now assert_emails 2 end def test_email_in_block assert_emails 1 do ContactMailer.welcome.deliver_now end assert_emails 2 do ContactMailer.welcome.deliver_now ContactMailer.welcome.deliver_later end end def test_no_emails_sent refute_emails ContactMailer.welcome.deliver_now assert_emails 1 end def test_no_emails_in_block refute_emails do # No emails should be sent from this block end end def test_enqueued_emails assert_enqueued_emails 0 ContactMailer.welcome.deliver_later assert_enqueued_emails 1 end def test_enqueued_email_with_specific_mailer assert_enqueued_email_with ContactMailer, :welcome do ContactMailer.welcome.deliver_later end end def test_enqueued_email_with_arguments assert_enqueued_email_with ContactMailer, :welcome, args: ["Hello", "Goodbye"] do ContactMailer.welcome("Hello", "Goodbye").deliver_later end end def test_parameterized_email assert_enqueued_email_with ContactMailer, :welcome, args: { email: 'user@example.com' } do ContactMailer.with(email: 'user@example.com').welcome.deliver_later end end def test_no_enqueued_emails refute_enqueued_emails ContactMailer.welcome.deliver_later assert_enqueued_emails 1 end end # Using spec expectations describe ContactMailer do it "creates welcome email" do mail = ContactMailer.welcome mail.subject.must_equal "Welcome" mail.to.must_equal ["to@example.org"] mail.from.must_equal ["from@example.com"] end it "sends emails" do must_have_emails 1 do ContactMailer.welcome.deliver_now end end it "sends no emails initially" do wont_have_emails ContactMailer.welcome.deliver_now must_have_emails 1 end it "enqueues emails for later delivery" do must_have_enqueued_emails 1 do ContactMailer.welcome.deliver_later end end it "enqueues specific email" do must_enqueue_email_with ContactMailer, :welcome do ContactMailer.welcome.deliver_later end end end ``` -------------------------------- ### Controller Response Assertions in Rails (Minitest) Source: https://context7.com/minitest/minitest-rails/llms.txt Tests controller actions to verify HTTP response status codes and redirects. It checks for success, redirects, and specific status codes like 404 or 422. Supports both standard Minitest and spec-style expectations. ```ruby require "test_helper" class PagesControllerTest < ActionDispatch::IntegrationTest def test_index_responds_with_success get pages_url assert_response :success end def test_redirect_to_login get protected_page_url assert_response :redirect assert_redirected_to login_url end def test_not_found_response get page_url(id: 9999) assert_response :missing # 404 end def test_specific_status_codes get api_items_url assert_response 200 post api_items_url, params: { invalid: true } assert_response 422 # Unprocessable Entity end end # Using spec expectations describe PagesController do it "responds with success" do get pages_url must_respond_with :success end it "redirects to login" do get protected_page_url must_redirect_to login_url end end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.