Minitest spec custom mapper

I have a line in my test:

page.has_reply?("my reply").must_equal true

and to make it more readable, I want to use a custom connector:

page.must_have_reply "my reply"

Based on the docs for https://github.com/zenspider/minitest-matchers I expect that I need to write a match that looks something like this:

def have_reply(text)
  subject.has_css?('.comment_body', :text => text)
end
MiniTest::Unit::TestCase.register_matcher :have_reply, :have_reply

The problem is that I don’t see how to get a link to an object (i.e. a page object). The docs say, “The subject of the note should be the first argument in the statement,” but it really doesn't help.

+5
source share
2 answers

, , matches?, failure_message_for_should, failure_message_for_should_not. matches? .

class MyMatcher
  def initialize(text)
    @text = text
  end

  def matches? subject
    subject =~ /^#{@text}.*/
  end

  def failure_message_for_should
    "expected to start with #{@text}"
  end

  def failure_message_for_should_not
    "expected not to start with #{@text}"
  end
end

def start_with(text)
  MyMatcher.new(text)
end
MiniTest::Unit::TestCase.register_matcher :start_with, :start_with

describe 'something' do
  it 'must start with...' do
    page = 'my reply'
    page.must_start_with 'my reply'
    page.must_start_with 'my '
  end
end
+6

, . - , assert. , has_reply?, :

assert page.has_reply?("my reply")

must_have_reply, . , has_reply?. , .

" (.. )". , must_have_reply. , this subject. , . , (assert_equal, refute_equal) (must_be_equal, wont_be_equal). Matcher, API- Matcher.

API. , , Cabybara have_css matcher, Capybara HaveSelector API. Matchers , HasSelector.

# Require Minitest Matchers to make this all work
require "minitest/matchers"
# Require Capybara matchers so you can use them
require "capybara/rspec/matchers"

# Create your own matchers module
module YourApp
  module Matchers
    def have_reply text
      # Return a properly configured HaveSelector instance
      Capybara::RSpecMatchers::HaveSelector.new(:css, ".comment_body", :text => text)
    end

    # Register module using minitest-matcher syntax
    def self.included base
      instance_methods.each do |name|
        base.register_matcher name, name
      end
    end
  end
end

minitest_helper.rb Matchers, . ( .)

class MiniTest::Rails::ActiveSupport::TestCase
  # Include your module in the test case
  include YourApp::Matchers
end

Minitest Matchers . :

def test_using_an_assertion
  visit root_path
  assert_have_reply page, "my reply"
end

:

it "is an expectation" do
  visit root_path
  page.must_have_reply "my reply"
end

, , :

describe "with a subject" do
  before  { visit root_path }
  subject { page }

  it { must have_reply("my reply") }
  must { have_reply "my reply" }
end

. "gem minitest-matchers", ' >= 1.2.0', register_matcher .

+1

All Articles