-
Notifications
You must be signed in to change notification settings - Fork 6
testing
Nagendra Dhanakeerthi edited this page Oct 30, 2024
·
1 revision
# 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# 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
endclass 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
enddef 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- Always use WebMock in tests
- Test all error scenarios
- Verify request parameters
- Test timeouts and retries
- Use proper test helpers
- Keep tests isolated