Friday, 15 July 2011

ruby on rails 3 - Testing Custom Validate Action for Nested Attributes -



ruby on rails 3 - Testing Custom Validate Action for Nested Attributes -

i've got custom action validate number of kid attributes. i've set in parent's model:

class location < activerecord::base has_many :blacklisted accepts_nested_attributes_for :blacklisted, :reject_if => lambda { |a| a[:mac].blank? }, :allow_destroy => true ... validate :check_blacklisted_clients_count private def check_blacklisted_clients_count if self.blacklisted.reject(&:marked_for_destruction?).count > 25 self.errors.add :base, "no more 25 blacklisted clients allowed per location." end end

that works fine when add together through browser i'm trying test rspec , can't fail (or pass, whichever way @ it).

"should not allow 26 blacklisted macs", :focus => true loc = factorygirl.create(:location_full) 25.times loc.blacklisted.create(mac: '00:22:33:44:55:66') end loc.blacklisted.create(mac: '00:22:33:44:55:66') puts loc.blacklisted.count ......... end

(i know doesn't test yet - wanted create sure 25 created).

i'm assuming because there's no validation in blacklisted.rb model.

how can rspec test validation?

the straightforward approach write 1 spec adds fewer 25 blacklisted macs, , 1 adds more 25, , test former valid , latter invalid.

depending on how sense spec runtimes, might work out fine. if test slow, might want utilize stubs. instance:

let(:location) { location.new } "should invalid more 25 blacklisted macs" location.stub_chain(:blacklisted, :reject, :count) { 26 } location.should be_invalid location.errors(:base).should include("no more 25 blacklisted clients allowed per location.") end

using stubs has disadvantages--specs more brittle, , coupled implementation closely. on other hand, if checking 25,000 macs, testing real objects might not feasible.

ruby-on-rails-3 rspec factory-girl

No comments:

Post a Comment