ruby on rails - Validate presence of shipping address unless it's same as billing address -
i have in order class. want validate presence of shipping_address
unless it's same billing_address
. specs keep failing, however.
class order < activerecord::base attr_writer :ship_to_billing_address belongs_to :billing_address, class_name: 'address' belongs_to :shipping_address, class_name: 'address' accepts_nested_attributes_for :billing_address, :shipping_address validates :shipping_address, presence: true, unless: -> { self.ship_to_billing_address? } def ship_to_billing_address @ship_to_billing_address ||= true end def ship_to_billing_address? self.ship_to_billing_address end end
but keep getting failed specs (expected example not valid):
describe "shipping_address_id" context "when shipping address different billing address" before { @order.ship_to_billing_address = false } it_behaves_like 'a foreign key', :shipping_address_id end end shared_examples 'a foreign key' |key| "can't nil, blank, or not int" [nil, "", " ", "a", 1.1].each |value| @order.send("#{key}=", value) @order.should_not be_valid end end end
form code:
= f.check_box :ship_to_billing_address | use shipping address billing address.
your ship_to_billing_address
method implementation wrong. sets @ship_to_billing_address
true
if set false
before. more correct implementation:
def ship_to_billing_address @ship_to_billing_address = true if @ship_to_billing_address.nil? @ship_to_billing_address end
examples:
irb(main):001:0> class order irb(main):002:1> attr_writer :stba irb(main):003:1> def stba irb(main):004:2> @stba ||= true irb(main):005:2> end irb(main):006:1> end => nil irb(main):007:0> irb(main):008:0* o = order.new => #<order:0x8bbc24c> irb(main):009:0> o.stba = false => false irb(main):010:0> o.stba irb(main):011:0> class order2 irb(main):012:1> attr_writer :stba irb(main):013:1> def stba irb(main):014:2> if @stba.nil? irb(main):015:3> @stba = true irb(main):016:3> else irb(main):017:3* @stba irb(main):018:3> end irb(main):019:2> end irb(main):020:1> end => nil irb(main):021:0> o = order2.new => #<order2:0x8b737e0> irb(main):022:0> o.stba = false => false irb(main):023:0> o.stba => false
Comments
Post a Comment