2

I am having trouble understanding what to test in the case below and how to do it.

I have the following instance method on Address model

validate :address, on: [:create, :update]

def address
    check = CalendarEventLocationParsingWorker.new.perform("", self.structured, true )
    if check[:code] != 0
      errors.add(:base,"#{self.kind.capitalize} Address couldn't be analysed, please fill up as much fields as possible.")
    else
      self.lat = check[:coords]["lat"]
      self.lon = check[:coords]["lng"]
    end
  end

Basically its a method called on create and update hooks and checks with a third party API if the address is valid. How can i test this in isolation without making an actual call to the 3rd party api but rather simulate the response?

I read about mocks and stubs but i do not quite get them yet. Any insight is welcome. Using Rspec, shoulda matchers and factory girl.

Petros Kyriakou
  • 5,214
  • 4
  • 43
  • 82

2 Answers2

1

Use webmock or vcr gems to stub external api responses

An example with webmock:

stub_request(:get, "your external api url")
  .to_return(code: 0, coords: { lat: 1, lng: 2 })

# test your address method here

With vcr you can run your test once and it will make an actual call to external api, record its resonse to .yml file and then reuse it in all later tests. If external api response changes you can just delete .yml file and record a new sample response.

Slava.K
  • 3,073
  • 3
  • 17
  • 28
0

You can stub perform method on any instance of CalendarEventLocationParsingWorker to return desired value

Syntax:

allow_any_instance_of(Class).to receive(:method).and_return(:return_value)

Ex:

allow_any_instance_of(CalendarEventLocationParsingWorker).to receive(:perform).and_return({code: 0})

Refer: Allow a message on any instance of a class

Sujan Adiga
  • 1,331
  • 1
  • 11
  • 20