rspecshoulda

RSpec / Shoulda validate_presence_of multiple attributes syntax


When testing for validate_presence_of for multiple attributes using Shoulda / RSpec I get these long and repeating blocks of code likes this:

it { should validate_presence_of(:text) }
it { should validate_presence_of(:user) }
it { should validate_presence_of(:commentable) }
[...]

Is there a way to DRY this up? Something like this:

it { should validate_presence_of(:text, :user, :commentable,...) }

Solution

  • As far as I know, there is nothing built-in to Shoulda for this. Often you will want to chain options to the shoulda macros, e.g. .with_message(...), so your syntax suggestion wouldn't be possible for those cases.

    You could instead do something like:

    [:text, :user, :commentable].each do |field|
      it { should validate_presence_of(field) }
    end
    

    However, I wouldn't worry too much about having a little bit of duplication in your test suite for the sake of easier reading and maintaining.