Vita Rara: A Life Uncommon

Rspec & Shoulda: Specifying the Object Under Test

Categories: | |

Today we needed to test conditional validations on a model. We're using RSpec with the Shoulda macros to do this. Our model looks something like:

class Person < ActiveRecord::Base
  validates_presence_of :login, :if => :is_user?

Using the normal Shoulda macros the following will fail because is_user if false and the validation will not run.

it { should validate_presence_of(:login) } 

To make the validation we need to instantiate the object under test, the "subject", and set the is_user property.

describe "a person who is a user" do 
  before(:each) do
    @subject =
    @subject.is_user = true

  it { should validate_presence_of(:login) } 

With that our validation is run and our spec passes.