Skip to content

Unit Tests

Mario Izquierdo edited this page Sep 17, 2018 · 3 revisions

Twirp already takes care of HTTP routing and serialization, you don't really need to test that part.

Your tests should focus on the handler (your code). For convenience, Twirp services have the method:

.call_rpc(rpc_method, attrs={}, env={})

When using .call_rpc, service hooks are not called and exceptions are raised instead of being wrapped. Which is better to easily identify issues during test runs. The env should include fake data that is used by the handler, replicating middleware and before hooks. Example:

require 'minitest/autorun'

class HelloWorldHandlerTest < Minitest::Test

  def test_hello_responds_with_name
    resp = service.call_rpc :Hello, name: "World"
    assert_equal "Hello World", resp.message
  end

  def test_hello_name_is_mandatory
    twerr = service.call_rpc :Hello, name: ""
    assert_equal :invalid_argument, twerr.code
  end

  def test_hello_bad_auth_token
    # simulate a bad env[:auth_token] from before hook
    twerr = service.call_rpc :Hello, {name: "World"}, auth_token: "BAD_USER"
    assert_equal :permission_denied, twerr.code
  end

  def service
    handler = HelloWorldHandler.new()
    Example::HelloWorldService.new(handler)
  end
end
Clone this wiki locally