Tom Stuart
2009-Aug-26 07:38 UTC
[rspec-users] metaprogrammatically generating spec examples
On 25 Aug 2009, at 23:39, Joaquin Rivera Padron wrote:> where you iterate over an array of known required attributes and > then generate the typical %{it ''should require required attribute''} > spec example. That''s easy with shoulda, but in this case the > validations are contextual, they have the :if => xxx option, and > shoulda doesn''t support them (yet) > If not answering my former question: how you attack normally this > problem?There''s no reason to avoid the shoulda macros. Using :if just means that, in some contexts (e.g. when #active? returns true) @the_instance.should validate_presence_of(:name), and in other contexts (e.g. when #active? returns false) @the_instance.should_not validate_presence_of(:name). Shoulda isn''t going to be able to "support" :if, because in general it''s not possible to automatically construct a context in which the :if condition is definitely true or definitely false -- that''s your job, not Shoulda''s. You shouldn''t try to check the two different contexts with a single example. So, instead of just listing the attribute names, find a way to pair the attribute names with enough information to construct pairs of contexts in which you expect the validation to respectively fire and not fire. For example, if all of your :if arguments are actually just method names like :active? (rather than being blocks), you could say "REQ_ATTRS = [[:name, :active?], [:other, :need_other?]] ; REQ_ATTRS.each do |req_attr, if_method| ... end" and, inside the block, write one example that stubs the method to return true and checks that the validation fires, then write another example that stubs the method to return false and checks the validation doesn''t fire. Cheers, -Tom