|
19 | 19 | expect(result["B2"]).to include("fascinates her.") |
20 | 20 | end |
21 | 21 | end |
| 22 | + |
| 23 | + describe "#expand_with_ai" do |
| 24 | + it "parses JSON response from OpenAI" do |
| 25 | + fake_client = instance_double(OpenAI::Client) |
| 26 | + allow(OpenAI::Client).to receive(:new).and_return(fake_client) |
| 27 | + allow(fake_client).to receive(:chat).and_return( |
| 28 | + { |
| 29 | + "choices" => [ |
| 30 | + { "message" => { "content" => '{"A1":"Hello."}' } } |
| 31 | + ] |
| 32 | + } |
| 33 | + ) |
| 34 | + |
| 35 | + expander = described_class.new |
| 36 | + result = expander.expand_with_ai("Hello") |
| 37 | + |
| 38 | + expect(result["A1"]).to eq("Hello.") |
| 39 | + end |
| 40 | + |
| 41 | + it "returns empty hash when OpenAI response is missing content" do |
| 42 | + fake_client = instance_double(OpenAI::Client) |
| 43 | + allow(OpenAI::Client).to receive(:new).and_return(fake_client) |
| 44 | + allow(fake_client).to receive(:chat).and_return({}) |
| 45 | + |
| 46 | + expander = described_class.new |
| 47 | + |
| 48 | + expect(expander.expand_with_ai("Hello")).to eq({}) |
| 49 | + end |
| 50 | + |
| 51 | + it "returns empty hash when OpenAI response contains invalid JSON" do |
| 52 | + fake_client = instance_double(OpenAI::Client) |
| 53 | + allow(OpenAI::Client).to receive(:new).and_return(fake_client) |
| 54 | + allow(fake_client).to receive(:chat).and_return( |
| 55 | + { |
| 56 | + "choices" => [ |
| 57 | + { "message" => { "content" => "not-json" } } |
| 58 | + ] |
| 59 | + } |
| 60 | + ) |
| 61 | + |
| 62 | + expander = described_class.new |
| 63 | + |
| 64 | + expect(expander.expand_with_ai("Hello")).to eq({}) |
| 65 | + end |
| 66 | + |
| 67 | + it "sanitizes the base sentence before sending to OpenAI" do |
| 68 | + fake_client = instance_double(OpenAI::Client) |
| 69 | + allow(OpenAI::Client).to receive(:new).and_return(fake_client) |
| 70 | + |
| 71 | + captured_prompt = nil |
| 72 | + allow(fake_client).to receive(:chat) do |params| |
| 73 | + captured_prompt = params.dig(:parameters, :messages, 0, :content) |
| 74 | + { |
| 75 | + "choices" => [ |
| 76 | + { "message" => { "content" => '{"A1":"Hi."}' } } |
| 77 | + ] |
| 78 | + } |
| 79 | + end |
| 80 | + |
| 81 | + expander = described_class.new |
| 82 | + expander.expand_with_ai("O'Hara\n<script>") |
| 83 | + |
| 84 | + expect(captured_prompt).not_to include("\n") |
| 85 | + expect(captured_prompt).to include("\"O'Hara <script>\"") |
| 86 | + end |
| 87 | + end |
22 | 88 | end |
0 commit comments