RSpec : Shoulda Matcher : for Beginners : How things happen?

If you are new to TDD then installing and configuring for TDD is not what I will be talking about. Today, in this post I will talk about how every spec/example is evaluated by RSpec.

lets see an example for Applicant Model

RSpec.describe Applicant, type: :model do
it { validate_presence_of(:first_name) }
it { validate_presence_of(:last_name) }
it { validate_presence_of(:email) }
it { validate_presence_of(:phone_number) }
it { validate_presence_of(:gender) }
it { validate_presence_of(:job_id) }
it { validate_presence_of(:address) }
it { validate_presence_of(:city) }
it { validate_presence_of(:state) }

What is happening under the hood?

Subject : Every expectation requires a subject to operate on, just like doctors calling ‘subject’ to the patient they are going to operate on. By default ‘it’ method takes the class defined in the closed ‘describe’ block. Here in this case ‘Applicant’ model is the subject by default.

it { validate_presence_of(:email) }

Expectation: In the above expectation, Applicant model is expected to have a validation like below in the file `models/applicant.rb`

validates_presence_of :email

Main point is, How test code knows that this validation is set in the model or not?

– Does it parse the whole model’s code and checks?

– No, actually what happens is, it tries to create a record in the test database using data via fixtures or library such as ‘factory_girl‘. It expects the ActiveRecord to throw an error such as  ‘Email can’t be blank’. In fact to test the presence it tries to save the field empty  however it may fill other fields and it does not matter because it checks the error in the ’email’ field only.

– Note: if you have changed or expect your validation message to be like

it { validate_presence_of(:email).with_message('Bro, email is required' }

respective validation in model should be like

validates_presence_of :email, message: 'Bro, email is required'

– Main point is, if you do not mention validation message in the expectation then, RSpec expects the default validation message of ActiveRecords itself. So, don’t forget to mention the message in-case needed.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s