Tony Han
Tony Han

Reputation: 2230

Which is a better way to test validations of ActiveRecord using rspec?And why?

I'm going to test a model, like this;

class Post < ActiveRecord::Base
  validates_presence_of :title
  # ...
end

I find two main ways to test the validation:

1.Use thoughtbot's shoulda gem https://github.com/thoughtbot/shoulda

describe Post do
  it { should validate_presence_of(:title) }
end

2.Test the validations directly, as the way in the book

describe Post do
  it "must has title" do
    post = Post.create
    expect(post).not_to be_valid
end

So I wonder which is a better way and why. thanks in advance.

Upvotes: 0

Views: 39

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37409

The first test validates that Post declared validates_presence_of :title, and the second test validates that when Post declares validates_presence_of :title, and an instance has no title, the instance will not be valid.

On the one hand, since there is no need to test the internals of validates_presence_of, the more correct test, should be the first one.

On the other hand, it can be claimed that the first test counts on an implementation detail (the usage of a specific feature), while the second one tests behavior, so it is more correct.

So both use-cases have rationalizations.

I personally prefer the first one.

Edit

I've dug a bit inside the shoulda implementation, and it actually tests by setting a nil value to the instance, and checking if it has correct errors, so actually, it does check for behavior. In that case, definitely you should use it.

Upvotes: 1

Related Questions