Shoulda/RSpec matchers - conditional validation

Ruby on-RailsRubyRspecShoulda

Ruby on-Rails Problem Overview


In my code I had the following validation with Shoulda matchers, which works fine:

it { should validate_presence_of(:name) }

In my model, I've added the condition to my validation:

validates_presence_of :name, :if => eligible?

Is it possible to reflect it in the validations?

I've tried looking at documentation for shoulda matchers, but haven't been able to locate the solution.

Many thanks!

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

It doesn't appear that shoulda_matchers does this, but it's easy enough to write it yourself::

  context "if eligible" do
    before { allow(subject).to receive(:eligible?).and_return(true) }
    it { should validate_presence_of(:name) }
  end
  
  context "if ineligible" do
    before { allow(subject).to receive(:eligible?).and_return(false) }
    it { should_not validate_presence_of(:name) }
  end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionalexs333View Question on Stackoverflow
Solution 1 - Ruby on-RailszeteticView Answer on Stackoverflow