Skip to content

testing

Nagendra Dhanakeerthi edited this page Oct 30, 2024 · 1 revision

Testing Guide

Test Setup

Configuration

# test/test_helper.rb
require 'minitest/autorun'
require 'webmock/minitest'

class TestCase < Minitest::Test
  def setup
    @client = ChatGPT::Client.new('test-key')
    WebMock.disable_net_connect!
  end
end

Mock Helpers

# test/test_helper.rb
module TestHelpers
  def stub_chat_request
    stub_request(:post, "https://api.openai.com/v1/chat/completions")
      .to_return(
        status: 200,
        body: chat_response_body,
        headers: { 'Content-Type' => 'application/json' }
      )
  end

  def stub_completions_request
    stub_request(:post, %r{https://api\.openai\.com/v1/engines/.*/completions})
      .to_return(
        status: 200,
        body: completion_response_body,
        headers: { 'Content-Type' => 'application/json' }
      )
  end

  private

  def chat_response_body
    {
      "choices" => [{
        "message" => {
          "role" => "assistant",
          "content" => "Test response"
        }
      }]
    }.to_json
  end

  def completion_response_body
    {
      "choices" => [{
        "text" => "Test completion"
      }]
    }.to_json
  end
end

Example Tests

Chat API Tests

class TestChat < TestCase
  include TestHelpers

  def test_basic_chat
    stub_chat_request
    response = @client.chat([
      { role: "user", content: "Hello" }
    ])
    
    assert_equal "Test response", 
      response["choices"][0]["message"]["content"]
  end

  def test_chat_with_parameters
    stub_chat_request
    response = @client.chat(
      [{ role: "user", content: "Hello" }],
      { temperature: 0.7 }
    )
    
    assert response["choices"].length > 0
  end
end

Error Tests

def test_authentication_error
  stub_request(:post, /api\.openai\.com/)
    .to_return(
      status: 401,
      body: { error: { message: "Invalid key" } }.to_json
    )

  assert_raises(ChatGPT::AuthenticationError) do
    @client.chat([{ role: "user", content: "Hello" }])
  end
end

Best Practices

  1. Always use WebMock in tests
  2. Test all error scenarios
  3. Verify request parameters
  4. Test timeouts and retries
  5. Use proper test helpers
  6. Keep tests isolated
Clone this wiki locally