minitest-spec-rails

repository·master·Indexed 19 days ago

https://github.com/metaskills/minitest-spec-rails

A library that allows Rails developers to use the Minitest::Spec BDD-style DSL within existing Rails test suites. It integrates with ActiveSupport::TestCase to enable spec-style testing for Models, Controllers, Integration tests, Mailers, View Helpers, and ActiveJob without requiring a complete rewrite. Key features include the `described_class` method for referencing the class under test and optional `mini_shoulda` integration for Shoulda-style syntax.

Tokens
3.2K
Snippets
16
Records
17
Agent score
64%

What's inside minitest-spec-rails

  1. Compare Minitest::Unit and Minitest::Spec assertion styles

    master

    Since Minitest::Spec is built on top of Minitest::Unit, you can mix and match assertion styles. You can use traditional assert_* methods or the Spec-style expect().must_* syntax interchangeably.

    StyleExample
    Minitest::Unitassert_equal 100, foo
    Minitest::Specexpect(foo).must_equal 100
    # Minitest::Unit Assertion Style:
    assert_equal 100, foo
    
    # Minitest::Spec Assertion Style:
    expect(foo).must_equal 100
  2. Install minitest-spec-rails

    master

    To use the Minitest::Spec DSL in your Rails application, add the gem to your :test group in the Gemfile. The version you choose depends on your Rails version.

    For Rails 4.1 to 6.0

    Use the master branch (tracking Rails 5.1 up to 6.x):

    group :test do
      gem 'minitest-spec-rails'
    end

    For Rails 3.x or 4.0

    Use the 3-x-stable branch:

    group :test do
      gem 'minitest-spec-rails', '~> 4.7'
    end
    group :test do
      gem 'minitest-spec-rails'
    end
  3. Configure mini_shoulda for Shoulda-style syntax

    master

    If you are migrating from Shoulda, you can enable mini_shoulda to provide aliases for context, should, and should_eventually.

    To enable this, add the following configuration to your test environment file:

    # In config/environments/test.rb
    config.minitest_spec_rails.mini_shoulda = true

    Once enabled, you can use syntax like this:

    class PostTests < ActiveSupport::TestCase
      setup    { @post = Post.create! :title => 'Test Title', :body => 'Test body' }
      teardown { Post.delete_all }
    
      should 'work' do
        @post.must_be_instance_of Post
      end
    
      context 'with a user' do
        should_eventually 'have a user' do
          # ...
        end
      end
    end
    # In config/environments/test.rb
    config.minitest_spec_rails.mini_shoulda = true
  4. Use spec-style syntax for ActionView Helper and View tests

    master

    The minitest-spec-rails gem automatically enables spec-style testing for classes that inherit from ActionView::TestCase. It registers spec types that match files ending in HelperTest, ViewTest, HelperSpec, or ViewSpec.

    When using these tests, you can use the described_class method (provided by the Descriptions module) to refer to the helper or view class being tested.

    # Example usage in a spec file
    # If your file is named app/helpers/application_helper_test.rb
    
    class ApplicationHelperTest < ActionView::TestCase
      describe "#some_helper_method" do
        it "returns expected value" do
          expect(described_class.some_helper_method(self)).to eq(true)
        end
      end
    end
  5. How ActionController tests are automatically configured

    master

    When using minitest-spec-rails, any class inheriting from ActionController::TestCase (or matching the pattern *ControllerTest) is automatically registered as a spec type. This enables the use of describe blocks and spec-style syntax within your controller tests. The library also provides a described_class method within these tests to automatically resolve the controller class being tested based on the test class name.

    # Example of how the automatic registration allows spec-style controller tests
    class UsersControllerTest < ActionController::TestCase
      describe "GET #index" do
        it "returns success" do
          get :index
          assert_response :success
        end
      end
    end
  6. Use spec-style syntax for ActiveJob tests

    master

    When using minitest-spec-rails, ActiveJob::TestCase is automatically configured to support spec-style testing. You can write tests for your jobs using describe blocks and access the job class via the described_class method.

    To trigger this behavior, ensure your test class inherits from ActiveJob::TestCase or follows the naming convention *JobTest.

    class MyJobTest < ActiveJob::TestCase
      describe MyJob do
        it "performs a task" do
          # test logic here
        end
      end
    end
  7. Use Spec Style for ActionDispatch Integration and Acceptance Tests

    master

    The minitest-spec-rails gem automatically enables Minitest::Spec behavior for Rails integration and acceptance tests. By including MiniTestSpecRails::Init::ActionDispatchBehavior into ActionDispatch::IntegrationTest, the library registers two spec types:

    1. Integration/Acceptance Tests: Any class whose name ends with IntegrationTest or AcceptanceTest is automatically treated as a spec type.
    2. Subclassing: Any class that inherits from an existing integration test class is also treated as a spec type.

    This allows you to use describe and it blocks within your standard Rails integration test files.

  8. Write Mailer tests using Spec style

    master

    When using minitest-spec-rails, ActionMailer::TestCase is automatically configured to support Spec-style syntax. You can define mailer tests by creating classes that inherit from ActionMailer::TestCase or by following the naming convention *MailerTest or *MailerSpec.

    When using the described_class method within a mailer spec, it will automatically resolve to the default mailer class based on the test's name.

    # Example of a Mailer Spec
    
    class UserMailerTest < ActionMailer::TestCase
      describe "welcome email" do
        it "sends the email" do
          # described_class will resolve to UserMailer
          mail = described_class.welcome_email(user)
          assert_emails 1
        end
      end
    end
  9. Troubleshoot assertion and mocking issues

    master

    Assertion Renames

    When upgrading from Test::Unit, note these changes:

    • assert_raise is now assert_raises.
    • assert_nothing_raised is no longer available.

    Mocha Compatibility

    If using mocha for mocking/stubbing, ensure you are on version 0.13.1 or higher. To suppress deprecation warnings in older Rails versions, add this to application.rb:

    require 'mocha/deprecation'
    Mocha::Deprecation.mode = :disabled

    Rails 3.0 Controller and Mailer Tests

    In Rails 3.0, controller and mailer tests require the tests interface to correctly set up assertions within describe blocks:

    class UsersControllerTest < ActionController::TestCase
      tests UsersController
    end
    
    class UserMailerTest < ActionMailer::TestCase
      tests UserMailer
    end
    require 'mocha/deprecation'
    Mocha::Deprecation.mode = :disabled
  10. Use the `described_class` method in Rails tests

    master

    The described_class method is available as both a class method and an instance method in any Rails test case. It returns the class being described, provided you follow Rails naming conventions for your tests. This is useful for building class-level macros (similar to Shoulda).

    It is guaranteed to work regardless of the nesting level of the describe block.

    class UserTest < ActiveSupport::TestCase
      described_class # => User
    
      it 'works here' do
        described_class # => User
      end
    
      describe 'nested' do
        it 'works here too' do
          described_class # => User
        end
      end
    end
  11. Configure minitest-spec-rails via Rails configuration

    master

    You can configure minitest-spec-rails within your Rails application configuration. The primary configuration key is config.minitest_spec_rails.

    Currently, the available configuration option is:

    • mini_shoulda: A boolean flag (defaults to false) that determines whether to load mini_shoulda integration support.
    # In your Rails configuration (e.g., config/environments/test.rb)
    Rails.application.configure do
      config.minitest_spec_rails.mini_shoulda = true
    end
  12. Use the Minitest::Spec DSL in Rails tests

    master

    The MiniTestSpecRails::DSL module provides a spec-style interface for Rails testing, allowing you to use describe, before, after, and test methods. It works by extending your test classes with ClassMethods and mapping spec-style lifecycle hooks to standard Minitest setup and teardown methods.

    Key DSL methods include:

    • describe(*args, &block): Defines a new spec block. It manages a description stack to allow nested descriptions.
    • before(_type = nil, &block): Maps to the Minitest setup method, executing the block before each test.
    • after(_type = nil, &block): Maps to the Minitest teardown method, executing the block after each test.
    • test(name, &block): A convenience method that converts a standard test name into an it block (e.g., test 'does something' { ... } becomes it 'does something' { ... }).
    • described_class: Returns the class being described in the current spec context.
    # Example of using the DSL methods
    describe User do
      before do
        @user = User.new(name: 'Alice')
      end
    
      after do
        @user = nil
      end
    
      test 'has a name' do
        assert_equal 'Alice', @user.name
      end
    end