Gem Version

RSpec matcher for testing ActiveRecord models with a fluent and clear language.


First, add to your Gemfile (preferably in the :test group):

gem 'rspec-be_valid_when_matcher'

Then, include RSpec::BeValidWhenMatcher in RSpec configuration:

RSpec.configure do |config|
  config.include RSpec::BeValidWhenMatcher

Or, directly in your model spec(s):

describe MyModel do
  include RSpec::BeValidWhenMatcher

  subject { build(:my_model) }

  describe '#header' do
    it { is_expected.not_to be_valid_when :header, nil }

Basic usage

Here's an example using rspec-be_valid_when_matcher:

RSpec.describe Person do
  subject { }

  it { be_valid_when :name, 'Frank', 'some text' }
  it { be_valid_when :age, 42, 'positive number' }
  it { is_expected.not_to be_valid_when :age, -1, 'negative number' }

The :name and :age are names of fields belonging to Person instance. If the matcher will fail, say for negative number check, it'll display the following message:


  1) Person should not be valid when #age is negative number (-1)
     Failure/Error: it { is_expected.not_to be_valid_when :age, -1, 'negative number' }

To keep the specs more readable #is(value, message) method can be used to separate field from expected value and optional message declaration like so:

RSpec.describe Person do
  subject { }

  it { be_valid_when(:name).is('Frank', 'some text') }
  it { be_valid_when(:age).is(42, 'positive number') }
  it { is_expected.not_to be_valid_when(:age).is(-1, 'negative number') }

Built-in checks


Test field validity with the nil value:

be_valid_when(:field).is_not_present     # Uses nil value


Test field validity with specific type values:

be_valid_when(:field).is_number 2          # Defaults to 42
be_valid_when(:field).is_fixnum 2          # Defaults to 42
be_valid_when(:field).is_bignum 1024**32   # Defaults to 42**13

MIT Licensed

See LICENSE file for full license text.