Shoulda/RSpec matchers - conditional validation
Asked Answered
S

1

72

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!

Seema answered 11/12, 2012 at 2:31 Comment(0)
J
154

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
Jaella answered 11/12, 2012 at 2:48 Comment(3)
With RSpec 3: before { allow(subject).to receive(: eligible?).and_return(true) }Translucent
Is this the best way to go? When we stub a method, we are bypassing the real logic, which can lead to tests that pass even though the code doesn't work as expected in a real scenario...Broth
@Broth I would argue that we are not "bypassing the real logic". The logic in the model is simple: if the return value of eligible? is true, perform the validation, if not, don't. That logic is exercised by this test. What isn't exercised is the behavior of the eligible? method, which presumably would be covered in different test.Jaella

© 2022 - 2024 — McMap. All rights reserved.