validates :if => :symbol

27 views
Skip to first unread message

Lawrence Pit

unread,
Sep 28, 2009, 10:42:04 PM9/28/09
to remarka...@googlegroups.com
Hi All,

I have heaps of this's:

validates_uniqueness_of :name, :if => :name_changed?

(to keep the nr of db queries to a minimum)

However, at the moment this cannot be tested with a one liner using
remarkable.

I was wondering, shouldn't we allow e.g. :

it { should validate_uniqueness_of(:name).if(:name_changed?) }

In essence, allow the :if and :unless if the argument is a symbol.

In this example I've given, the name_changed? method is implemented by
ActiveRecord, so I don't need further testing for that. But suppose you
had :if => :my_extra_validation, then you could add a specific test for
that method only.

Cheers,
Lawrence

José Valim

unread,
Sep 29, 2009, 6:53:08 AM9/29/09
to remarka...@googlegroups.com
The thing is: Remarkable mimics the validation process, so when you are validating the presence of something, remarkable sets that something to nil to see if an error appeared.

So, in order to :name_changed? to work, we would have to change the name somehow. And test when it's set and when it's not set. We could only do that, for symbols that we now the meaning, as :attribute_changed?. If the user gives other symbol, we won't know how to reproduce the content of the method specified by the symbol.

A quick way to achieve what you want is to use quick subjects:

describe :name => "changed" do
  validates_uniqueness_of :name
end

The output would be something like: when name is changed should validate uniqueness of name.
--
José Valim
Reply all
Reply to author
Forward
0 new messages