Skip to content

Instantly share code, notes, and snippets.

@hugomaiavieira
Last active December 16, 2015 01:59
Show Gist options
  • Save hugomaiavieira/5359356 to your computer and use it in GitHub Desktop.
Save hugomaiavieira/5359356 to your computer and use it in GitHub Desktop.
Controller action and route config for find and fill address fields using brcep gem
# controller action
def find_cep
begin
# Ex: ['Avenida', 'das Americas', 'Barra da Tijuca', 'Rio de Janeiro', 'RJ', 22640100]
address = BuscaEndereco.por_cep params[:cep]
street = "#{address.fetch(0)} #{address.fetch(1)}"
neighborhood = address.fetch(2)
city = address.fetch(3)
state = address.fetch(4)
data = {
street: street,
neighborhood: neighborhood,
city: city,
state: state
}
render json: data and return
rescue RuntimeError => e
render :json => { message: e.message }, :status => 500 and return
end
end
# config/routes.rb
get '/find_cep', to: 'application#find_cep'
# spec/controllers/application_controller_spec.rb
require 'spec_helper'
describe ApplicationController do
context 'find_cep' do
it 'should return a json with address fields if find sucessfully' do
BuscaEndereco.should_receive(:por_cep).with('22.640-100') {["Avenida", "das Americas", "Barra da Tijuca", "Rio de Janeiro", "RJ", "22640100"]}
get :find_cep, { :cep => '22.640-100' }
expect(response.body).to eq('{"street":"Avenida das Americas","neighborhood":"Barra da Tijuca","city":"Rio de Janeiro","state":"RJ"}')
end
it 'should return a json with an error if does not find sucessfully' do
BuscaEndereco.should_receive(:por_cep).with('00.000-000') { raise(RuntimeError, 'O CEP informado possui um formato invalido.')}
get :find_cep, { :cep => '00.000-000' }
expect(response.body).to eq('{"message":"O CEP informado possui um formato invalido."}')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment