• Stars
    star
    3,469
  • Rank 12,276 (Top 0.3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 13 years ago
  • Updated 19 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple one-liner tests for common Rails functionality

Shoulda Matchers Gem Version Build Status Total Downloads Downloads

shoulda-matchers

Shoulda Matchers provides RSpec- and Minitest-compatible one-liners to test common Rails functionality that, if written by hand, would be much longer, more complex, and error-prone.

Quick links

๐Ÿ“– Read the documentation for the latest version. ๐Ÿ“ข See what's changed in recent versions.

Table of contents

Getting started

RSpec

Start by including shoulda-matchers in your Gemfile:

group :test do
  gem 'shoulda-matchers', '~> 6.0'
end

Then run bundle install.

Now you need to configure the gem by telling it:

  • which matchers you want to use in your tests
  • that you're using RSpec so that it can make those matchers available in your example groups

Rails apps

If you're working on a Rails app, simply place this at the bottom of spec/rails_helper.rb (or in a support file if you so choose):

Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :rails
  end
end

Non-Rails apps

If you're not working on a Rails app, but you still make use of ActiveRecord or ActiveModel in your project, you can still use this gem too! In that case, you'll want to place the following configuration at the bottom of spec/spec_helper.rb:

Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec

    # Keep as many of these lines as are necessary:
    with.library :active_record
    with.library :active_model
  end
end

Minitest

If you're using our umbrella gem Shoulda, then make sure that you're using the latest version:

group :test do
  gem 'shoulda', '~> 4.0'
end

Otherwise, add shoulda-matchers to your Gemfile:

group :test do
  gem 'shoulda-matchers', '~> 6.0'
end

Then run bundle install.

Now you need to configure the gem by telling it:

  • which matchers you want to use in your tests
  • that you're using Minitest so that it can make those matchers available in your test case classes

Rails apps

If you're working on a Rails app, simply place this at the bottom of test/test_helper.rb:

Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :minitest
    with.library :rails
  end
end

Non-Rails apps

If you're not working on a Rails app, but you still make use of ActiveRecord or ActiveModel in your project, you can still use this gem too! In that case, you'll want to place the following configuration at the bottom of test/test_helper.rb:

Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :minitest

    # Keep as many of these lines as are necessary:
    with.library :active_record
    with.library :active_model
  end
end

Usage

Most of the matchers provided by this gem are useful in a Rails context, and as such, can be used for different parts of a Rails app:

As the name of the gem indicates, most matchers are designed to be used in "one-liner" form using the should macro, a special directive available in both RSpec and Shoulda. For instance, a model test case may look something like:

# RSpec
RSpec.describe MenuItem, type: :model do
  describe 'associations' do
    it { should belong_to(:category).class_name('MenuCategory') }
  end

  describe 'validations' do
    it { should validate_presence_of(:name) }
    it { should validate_uniqueness_of(:name).scoped_to(:category_id) }
  end
end

# Minitest (Shoulda)
class MenuItemTest < ActiveSupport::TestCase
  context 'associations' do
    should belong_to(:category).class_name('MenuCategory')
  end

  context 'validations' do
    should validate_presence_of(:name)
    should validate_uniqueness_of(:name).scoped_to(:category_id)
  end
end

See below for the full set of matchers that you can use.

On the subject of subject

For both RSpec and Shoulda, the subject is an implicit reference to the object under test, and through the use of should as demonstrated above, all of the matchers make use of subject internally when they are run. A subject is always set automatically by your test framework in any given test case; however, in certain cases it can be advantageous to override it. For instance, when testing validations in a model, it is customary to provide a valid model instead of a fresh one:

# RSpec
RSpec.describe Post, type: :model do
  describe 'validations' do
    # Here we're using FactoryBot, but you could use anything
    subject { build(:post) }

    it { should validate_presence_of(:title) }
  end
end

# Minitest (Shoulda)
class PostTest < ActiveSupport::TestCase
  context 'validations' do
    subject { build(:post) }

    should validate_presence_of(:title)
  end
end

When overriding the subject in this manner, then, it's important to provide the correct object. When in doubt, provide an instance of the class under test. This is particularly necessary for controller tests, where it is easy to accidentally write something like:

RSpec.describe PostsController, type: :controller do
  describe 'GET #index' do
    subject { get :index }

    # This may work...
    it { should have_http_status(:success) }
    # ...but this will not!
    it { should permit(:title, :body).for(:post) }
  end
end

In this case, you would want to use before rather than subject:

RSpec.describe PostsController, type: :controller do
  describe 'GET #index' do
    before { get :index }

    # Notice that we have to assert have_http_status on the response here...
    it { expect(response).to have_http_status(:success) }
    # ...but we do not have to provide a subject for render_template
    it { should render_template('index') }
  end
end

Availability of RSpec matchers in example groups

Rails projects

If you're using RSpec, then you're probably familiar with the concept of example groups. Example groups can be assigned tags order to assign different behavior to different kinds of example groups. This comes into play especially when using rspec-rails, where, for instance, controller example groups, tagged with type: :controller, are written differently than request example groups, tagged with type: :request. This difference in writing style arises because rspec-rails mixes different behavior and methods into controller example groups vs. request example groups.

Relying on this behavior, Shoulda Matchers automatically makes certain matchers available in certain kinds of example groups:

  • ActiveRecord and ActiveModel matchers are available only in model example groups, i.e., those tagged with type: :model or in files located under spec/models.
  • ActionController matchers are available only in controller example groups, i.e., those tagged with type: :controller or in files located under spec/controllers.
  • The route matcher is available in routing example groups, i.e., those tagged with type: :routing or in files located under spec/routing.
  • Independent matchers are available in all example groups.

As long as you're using Rails, you don't need to worry about these details โ€” everything should "just work".

Non-Rails projects

What if you are using ActiveModel or ActiveRecord outside of Rails, however, and you want to use model matchers in a certain example group? Then you'll need to manually include the module that holds those matchers into that example group. For instance, you might have to say:

RSpec.describe MySpecialModel do
  include Shoulda::Matchers::ActiveModel
  include Shoulda::Matchers::ActiveRecord
end

If you have a lot of similar example groups in which you need to do this, then you might find it more helpful to tag your example groups appropriately, then instruct RSpec to mix these modules into any example groups that have that tag. For instance, you could add this to your rails_helper.rb:

RSpec.configure do |config|
  config.include(Shoulda::Matchers::ActiveModel, type: :model)
  config.include(Shoulda::Matchers::ActiveRecord, type: :model)
end

And from then on, you could say:

RSpec.describe MySpecialModel, type: :model do
  # ...
end

should vs is_expected.to

In this README and throughout the documentation, you'll notice that we use the should form of RSpec's one-liner syntax over is_expected.to. Beside being the namesake of the gem itself, this is our preferred syntax as it's short and sweet. But if you prefer to use is_expected.to, you can do that too:

RSpec.describe Person, type: :model do
  it { is_expected.to validate_presence_of(:name) }
end

Matchers

Here is the full list of matchers that ship with this gem. If you need details about any of them, make sure to consult the documentation!

ActiveModel matchers

ActiveRecord matchers

ActionController matchers

  • filter_param tests parameter filtering configuration.
  • permit tests that an action places a restriction on the params hash.
  • redirect_to tests that an action redirects to a certain location.
  • render_template tests that an action renders a template.
  • render_with_layout tests that an action is rendered with a certain layout.
  • rescue_from tests usage of the rescue_from macro.
  • respond_with tests that an action responds with a certain status code.
  • route tests your routes.
  • set_session makes assertions on the session hash.
  • set_flash makes assertions on the flash hash.
  • use_after_action tests that an after_action callback is defined in your controller.
  • use_around_action tests that an around_action callback is defined in your controller.
  • use_before_action tests that a before_action callback is defined in your controller.

Routing matchers

  • route tests your routes.

Independent matchers

  • delegate_method tests that an object forwards messages to other, internal objects by way of delegation.

Extensions

Over time our community has created extensions to Shoulda Matchers. If you've created something that you want to share, please let us know!

Contributing

Have a fix for a problem you've been running into or an idea for a new feature you think would be useful? Take a look at the Contributing document for instructions on setting up the repo on your machine, understanding the codebase, and creating a good pull request.

Compatibility

Shoulda Matchers is tested and supported against Ruby 3.0+, Rails 6.1+, RSpec 3.x, and Minitest 5.x.

  • For Ruby < 2.4 and Rails < 4.1 compatibility, please use v3.1.3.
  • For Ruby < 3.0 and Rails < 6.1 compatibility, please use v4.5.1.

Versioning

Shoulda Matchers follows Semantic Versioning 2.0 as defined at https://semver.org.

Team

Shoulda Matchers is currently maintained by Pedro Paiva and Matheus Sales. Previous maintainers include Elliot Winkler, Gui Albuk, Jason Draper, Melissa Xie, Gabe Berke-Williams, Ryan McGeary, Joe Ferris, and Tammer Saleh.

Copyright/License

Shoulda Matchers is copyright ยฉ Tammer Saleh and thoughtbot, inc. It is free and opensource software and may be redistributed under the terms specified in the LICENSE file.

About thoughtbot

thoughtbot

This repo is maintained and funded by thoughtbot, inc. The names and logos for thoughtbot are trademarks of thoughtbot, inc.

We love open source software! See our other projects. We are available for hire.

More Repositories

1

guides

A guide for programming in style.
Ruby
9,327
star
2

bourbon

A Lightweight Sass Tool Set
Ruby
9,100
star
3

paperclip

Easy file attachment management for ActiveRecord
Ruby
9,055
star
4

laptop

A shell script to set up a macOS laptop for web and mobile development.
Shell
8,416
star
5

dotfiles

A set of vim, zsh, git, and tmux configuration files.
Shell
7,864
star
6

factory_bot

A library for setting up Ruby objects as test data.
Ruby
7,826
star
7

administrate

A Rails engine that helps you put together a super-flexible admin dashboard.
JavaScript
5,797
star
8

neat

A fluid and flexible grid Sass framework
Ruby
4,444
star
9

suspenders

A Rails template with our standard defaults, ready to deploy to Heroku.
Ruby
3,922
star
10

til

Today I Learned
3,903
star
11

clearance

Rails authentication with email & password.
Ruby
3,629
star
12

Argo

Functional JSON parsing library for Swift
Swift
3,495
star
13

high_voltage

Easily include static pages in your Rails app.
Ruby
3,141
star
14

rcm

rc file (dotfile) management
Perl
2,990
star
15

factory_bot_rails

Factory Bot โ™ฅ Rails
Ruby
2,972
star
16

shoulda

Makes tests easy on the fingers and the eyes
Ruby
2,184
star
17

expandable-recycler-view

Custom Android RecyclerViewAdapters that collapse and expand
Java
2,073
star
18

capybara-webkit

A Capybara driver for headless WebKit to test JavaScript web apps
Ruby
1,976
star
19

gitsh

An interactive shell for git
Ruby
1,957
star
20

Tropos

Weather and Forecasts for Humans
Swift
1,518
star
21

refills

[no longer maintained]
CSS
1,513
star
22

design-sprint

Product Design Sprint Material
1,415
star
23

bitters

Add a dash of pre-defined style to your Bourbon.
HTML
1,398
star
24

griddler

Simplify receiving email in Rails
Ruby
1,375
star
25

trail-map

Trails to help designers and developers learn various topics.
1,219
star
26

appraisal

A Ruby library for testing your library against different versions of dependencies.
Ruby
1,194
star
27

hotwire-example-template

A collection of branches that transmit HTML over the wire.
Ruby
989
star
28

parity

Shell commands for development, staging, and production parity for Heroku apps
Ruby
882
star
29

Runes

Infix operators for monadic functions in Swift
Swift
829
star
30

cocaine

A small library for doing (command) lines.
Ruby
788
star
31

fishery

A library for setting up JavaScript objects as test data
TypeScript
759
star
32

flutie

View helpers for Rails applications
Ruby
730
star
33

TBAnnotationClustering

Example App: How To Efficiently Display Large Amounts of Data on iOS Maps
Objective-C
728
star
34

ember-cli-rails

Unify your EmberCLI and Rails Workflows
Ruby
714
star
35

vim-rspec

Run Rspec specs from Vim
Vim Script
650
star
36

climate_control

Modify your ENV
Ruby
512
star
37

constable

Better company announcements
Elixir
511
star
38

carnival

An unobtrusive, developer-friendly way to add comments
Haskell
501
star
39

ruby-science

The reference for writing fantastic Rails applications
Ruby
494
star
40

Curry

Swift implementations for function currying
Swift
493
star
41

pacecar

Generated scopes for ActiveRecord classes
Ruby
437
star
42

hoptoad_notifier

Reports exceptions to Hoptoad
Ruby
408
star
43

fake_stripe

A Stripe fake so that you can avoid hitting Stripe servers in tests.
Ruby
393
star
44

json_matchers

Validate your JSON APIs
Ruby
381
star
45

Swish

Nothing but Net(working)
Swift
364
star
46

paul_revere

A library for "one off" announcements in Rails apps.
Ruby
298
star
47

stencil

Android library, written exclusively in kotlin, for animating the path created from text
Kotlin
282
star
48

Perform

Easy dependency injection for storyboard segues
Swift
280
star
49

superglue

A productive library for Classic Rails, React and Redux
JavaScript
275
star
50

upcase

Sharpen your programming skills.
Ruby
275
star
51

testing-rails

Source code for the Testing Rails book
HTML
269
star
52

proteus

[no longer maintained]
Ruby
254
star
53

Delta

Managing state is hard. Delta aims to make it simple.
Swift
246
star
54

foundry

Providing a new generation of vector assets and infinite possibility for the interactive web and mobile applications
CSS
233
star
55

limerick_rake

A collection of useful rake tasks.
Ruby
232
star
56

backbone-support

lumbar support
JavaScript
227
star
57

shoulda-context

Shoulda Context makes it easy to write understandable and maintainable tests under Minitest and Test::Unit within Rails projects or plain Ruby projects.
Ruby
219
star
58

terrapin

Run shell commands safely, even with user-supplied values
Ruby
216
star
59

Superb

Pluggable HTTP authentication for Swift.
Swift
203
star
60

jack_up

[DEPRECATED] Easy AJAX file uploading in Rails
Ruby
202
star
61

fistface

DIY @font-face web service.
Ruby
182
star
62

squirrel

Natural-looking Finder Queries for ActiveRecord
Ruby
178
star
63

sortable_table

Sort HTML tables in your Rails app.
Ruby
157
star
64

write-yourself-a-roguelike

Write Yourself A Roguelike: Ruby Edition
Ruby
155
star
65

pester

Automatically ask for a PR review
Ruby
147
star
66

jester

REST in Javascript
JavaScript
146
star
67

complexity

A command line tool to identify complex code
Rust
142
star
68

kumade

Heroku deploy tasks with test coverage (DEPRECATED, NO LONGER BEING DEVELOPED)
Ruby
137
star
69

proteus-middleman

[no longer maintained]
CSS
133
star
70

FunctionalJSON-swift

Swift
133
star
71

capybara_discoball

Spin up an external server just for Capybara
Ruby
128
star
72

tropos-android

Weather and Forecasts for Humans
Kotlin
128
star
73

ModalPresentationView

Remove the boilerplate of modal presentations in SwiftUI
Swift
125
star
74

react-native-typescript-styles-example

A template react native project for ergonomic styling structure and patterns.
TypeScript
123
star
75

vimulator

A JavaScript Vim simulator for demonstrations
JavaScript
119
star
76

bourne

[DEPRECATED] Adds test spies to mocha.
Ruby
114
star
77

formulator

A form library for Phoenix
Elixir
106
star
78

poppins

Gifs!
Objective-C
106
star
79

tailwindcss-aria-attributes

TailwindCSS variants for aria-* attributes
JavaScript
100
star
80

ghost-theme-template

A project scaffold for building ghost themes using gulp, node-sass, & autoprefixer
HTML
91
star
81

paperclip_demo

Paperclip demo application
Ruby
87
star
82

middleman-template

The base Middleman application used at thoughtbot, ready to deploy to Netlify.
CSS
86
star
83

proteus-jekyll

[no longer maintained]
CSS
84
star
84

report_card

metrics and CI are for A students.
Ruby
77
star
85

ios-sample-blender

Sample code for the Blending Modes blog post
Objective-C
76
star
86

yuri-ita

Create powerful interfaces for filtering, searching, and sorting collections of items.
Ruby
76
star
87

baccano

[no longer maintained]
HTML
74
star
88

goal-oriented-git

A practical book about using Git
HTML
73
star
89

ios-on-rails

A guide to building a Rails API and iOS app
HTML
72
star
90

art_vandelay

Art Vandelay is an importer/exporter for Rails 6.0 and higher.
Ruby
71
star
91

maybe_haskell

Programming without Null
HTML
71
star
92

redbird

A Redis adapter for Plug.Session
Elixir
67
star
93

maintaining-open-source-projects

A successful open source project is not only one that is original, solves a particular problem well, or has pristine code quality. Those are but the tip of the iceberg, which we'll thoroughly dissect with this book.
Shell
67
star
94

templates

Documentation templates for open source projects.
64
star
95

FOMObot

A slack bot to help with FOMO.
Haskell
61
star
96

BotKit

BotKit is a Cocoa Touch static library for use in iOS projects. It includes a number of helpful classes and categories that are useful during the development of an iOS application.
Objective-C
61
star
97

react-native-template

Template React Native project to be used with Cookiecutter
JavaScript
60
star
98

CombineViewModel

An implementation of the Model-View-ViewModel (MVVM) pattern using Combine.
Swift
59
star
99

flightdeck

Terraform modules for rapidly building production-grade Kubernetes clusters following SRE practices
HCL
55
star
100

design-for-developers-starter-kit

A starter project for design for developer students
CSS
54
star