ruby - how to verify length and numericality of an atribute in rails with Rspec -



ruby - how to verify length and numericality of an atribute in rails with Rspec -

i have client model first name, lastly name, , phone number. want allow user come in in phone number in format such 555-555-5555 or (555)555-5555 or 555.555.5555

here client model

class client < activerecord::base before_validation(on: :create) { format_phone_number } validates_presence_of :first_name, :last_name, :phone_number validates :phone_number, numericality: true, length: {minimum: 10} private def format_phone_number self.phone_number = phone_number.gsub(/[^0-9]/, "") if attribute_present?("phone_number") end end

the format_phone_number method strips out non-numeric characters before validation, want validate has length 10

and here spec

describe client { should validate_presence_of(:first_name)} { should validate_presence_of(:last_name)} { should validate_presence_of(:phone_number)} { should ensure_length_of(:phone_number).is_at_least(10) } describe "phone_number" "should remove non-numeric characters" bob = fabricate(:customer, first_name: "bob", last_name: "smith", phone_number: "555-777-8888" ) expect(bob.phone_number).to eq('5557778888') end end end

when run error

failure/error: { should ensure_length_of(:phone_number).is_at_least(10) } did not expect errors include "is short (minimum 10 characters)" when phone_number set "xxxxxxxxxx", got error: short (minimum 10 characters)

so seems rspec trying test length "xxxxxxxxxx" , , method stripping x's before object gets saved. improve way test or implement this?

this occurring because format_phone_number callback triggered before validation. while haven't utilize fabrication gem, the documentation indicates initializes activerecord object not phone call save or valid?. hence before_validation callback not triggered. seek adding valid? before rspec assertion:

it "should remove non-numeric characters" bob = fabricate(:customer, first_name: "bob", last_name: "smith", phone_number: "555-777-8888" ) bob.valid? expect(bob.phone_number).to eq('5557778888') end

alternatively can utilize after_initialize activerecord callback trigger formatting client object built:

class client < activerecord::base #... after_initialize :format_phone_number #... end

ruby-on-rails ruby rspec shoulda

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -