module RubyLLM::TestHelper
Lets a test script what the model replies, with no provider and no API key. Replies go through the real conversation loop, so streaming, tools, persistence, cost, and #cancel all behave as they do in production. Require it in your test helper, and include it like ActiveJob::TestHelper:
require "ruby_llm/test_helper" class SupportAgentTest < ActiveSupport::TestCase include RubyLLM::TestHelper test "answers" do stub_replies "Hello there", cost: 0.01 reply = SupportAgent.new.ask("Hi") assert_equal "Hello there", reply.content assert_equal 0.01, reply.cost.total end end
It also works in RSpec: config.include RubyLLM::TestHelper. A chatβs request reaches the stub. Other operations, such as RubyLLM.embed, still call their provider.
Public Instance Methods
# File lib/ruby_llm/test_helper.rb, line 107 def stub_replies(*replies, cost: nil, interval: nil) Script.stub(replies, { cost:, interval: }) end
Makes every chat answer with replies until the test ends, in order, repeating the last, instead of calling a provider. A String streams word by word, and tool_call asks the conversation loop to run a tool. cost: is what each reply reports, in dollars. interval: is the seconds between words, so a test can press Stop while a reply streams.
stub_replies "Hello there", cost: 0.01 stub_replies tool_call(:weather, city: "Berlin"), "It is sunny." stub_replies "A long reply", interval: 0.1
# File lib/ruby_llm/test_helper.rb, line 113 def tool_call(name, **arguments) ToolCall.new(id: "call_#{SecureRandom.hex(4)}", name: name.to_s, arguments:) end
Returns a reply that calls the tool name with arguments, for stub_replies.