Skip to content

Instantly share code, notes, and snippets.

@eliotsykes
Last active March 31, 2017 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliotsykes/e27e79062f7e540aefd399ae816b0e94 to your computer and use it in GitHub Desktop.
Save eliotsykes/e27e79062f7e540aefd399ae816b0e94 to your computer and use it in GitHub Desktop.
Extract Custom RSpec Matcher

Original

expect(page).to have_css("h3", text: "Expected text here...")
click_button "Submit"
expect(page).to(
  have_css("h3", text: "Expected text here..."),
  "stay on page on invalid form submit"
)

Extract custom matcher

expect(page).to be_new_user_page
click_button "Submit"
expect(page).to(be_new_user_page, "stay on page on invalid form submit")
...

Add this at the bottom of the *_spec.rb file, within the feature block:

require "rails_helper"

feature "..." do

  scenario "..." do
    ...
  end
  
  matcher :be_new_user_page do
    match_unless_raises do |page|
      # Added a path expectation to increase confidence we're on
      # the correct page.
      expect(page).to have_current_path "/expected/path/here"
      expect(page).to have_css "h3", text: "Expected text here..."
    end
  end
end

Further reading: https://www.wetestrails.com/blog/extract-matcher

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment