Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Adding the ":if" option to macros #135

guilherme opened this Issue Jul 21, 2012 · 1 comment


None yet
2 participants


Why the activerecord matchers don't have the 'if' condition to test? For example:

it { should validate_uniqueness_of(:a).if(:x) }
# or
it { should validate_uniqueness_of(:a).if(lambda { x }) }
# or 
it { should validate_uniqueness_of(:a).if(Proc.new) }

I thinking about how to implement this but i've came to a dilema:

  • It's not implemented on shoulda-matchers because it's a context of testing. For e.g. if i want to test if this validation occurs if a condition happens than i could do:

suppose i have on my model:

class MyModel < ActiveRecord::Base
    validates :attr, :uniqueness => true, :if => :happening_condition_attribute

context "happening condition" do

      subject { MyModel.new(:happening_condition_attribute => true) }

      it { should validate_uniqueness_of(:attr) }

  • It's not implemented on shoulda-matchers because it's hard to figure out what could be on: Proc.new or lambda blocks.
  • Dunno what more reasons to not have it.



jferris commented Jul 21, 2012

Having an if statement in a test is dangerous. For one, it means that you need to debug which branch of the condition you're in when you're trying to debug a failure. It means that it's easy to make a mistake in the condition, which will mean that you've written a self-verifying test that does nothing. It hides the complexity of the System Under Test. Lastly, it's often not clear how the setup should vary between one branch of the if and the other.

Instead, the recommended approach for testing conditions (both with validations and elsewhere) is to write two tests: one that tests the positive case, and one for the negative.

@jferris jferris closed this Jul 21, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment