kdweber89 kdweber89 - 4 months ago 20
Ruby Question

How to test a rails method through the rails console

I am having trouble testing specific zip codes in specific addresses. I have a concern that is inherited and validated in a model. It fixes another problem of users inputing default zip codes that do not match the states that they are located in. However I ultimately need to run a migration to fix any zip codes that have been flawed up until this point. Which brings me to my problem. Is there a way to test a specific concern, or method written in this concern through the console at all?

My concern is below.

module StateMatchesZipCodeConcern
extend ActiveSupport::Concern

def verify_zip_matches_state
return unless zip.present? && state.present?

state_search_result = query_zip_code

unless state_search_result.nil?
return if state_search_result.upcase == state.upcase
return if validate_against_multi_state_zip_codes
end
errors[:base] << "Please verify the address you've submitted. The postal code #{zip.upcase} is not valid for the state of #{state.upcase}"
false
end

private

def query_zip_code
tries ||= 3
Geocoder.search(zip).map(&:state_code).keep_if { |x| Address::STATES.values.include?(x) }.first
rescue Geocoder::OverQueryLimitError, Timeout::Error
retry unless (tries -= 1).zero?
end

def validate_against_multi_state_zip_codes
::Address::MULTI_STATE_ZIP_CODES[zip].try(:include?, state)
end
end


I've tried
User.last.address.validate_against_multi_state_zip_codes?
and wind up with a method missing. Would anybody know what I'm missing here?

Answer

I'm assuming you're including StateMatchesZipCodeConcern in your User model.

That means the method validate_against_multi_state_zip_codes will be a method on User instances.

You're trying to call this method on the return of the User's address method, which is what throws NoMethodError. In addition, you've made this method private so you won't be able to call it anyway.

Put the method above the private line in the module and call it like this: User.last.validate_against_multi_state_zip_codes?

Comments