Skip to main content

alef_e2e/codegen/
ruby.rs

1//! Ruby e2e test generator using RSpec.
2//!
3//! Generates `e2e/ruby/Gemfile` and `spec/{category}_spec.rb` files from
4//! JSON fixtures, driven entirely by `E2eConfig` and `CallConfig`.
5
6use crate::codegen::resolve_field;
7use crate::config::E2eConfig;
8use crate::escape::{ruby_string_literal, ruby_template_to_interpolation, sanitize_filename, sanitize_ident};
9use crate::field_access::FieldResolver;
10use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup, ValidationErrorExpectation};
11use alef_core::backend::GeneratedFile;
12use alef_core::config::ResolvedCrateConfig;
13use alef_core::hash::{self, CommentStyle};
14use alef_core::template_versions as tv;
15use anyhow::Result;
16use heck::ToSnakeCase;
17use std::collections::HashMap;
18use std::fmt::Write as FmtWrite;
19use std::path::PathBuf;
20
21use super::E2eCodegen;
22use super::client;
23
24/// Ruby e2e code generator.
25pub struct RubyCodegen;
26
27impl E2eCodegen for RubyCodegen {
28    fn generate(
29        &self,
30        groups: &[FixtureGroup],
31        e2e_config: &E2eConfig,
32        config: &ResolvedCrateConfig,
33        _type_defs: &[alef_core::ir::TypeDef],
34    ) -> Result<Vec<GeneratedFile>> {
35        let lang = self.language_name();
36        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
37
38        let mut files = Vec::new();
39
40        // Resolve call config with overrides.
41        let call = &e2e_config.call;
42        let overrides = call.overrides.get(lang);
43        let module_path = overrides
44            .and_then(|o| o.module.as_ref())
45            .cloned()
46            .unwrap_or_else(|| call.module.clone());
47        let class_name = overrides.and_then(|o| o.class.as_ref()).cloned();
48        let options_type = overrides.and_then(|o| o.options_type.clone());
49        let empty_enum_fields = HashMap::new();
50        let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields);
51        let result_is_simple = call.result_is_simple || overrides.is_some_and(|o| o.result_is_simple);
52
53        // Resolve package config.
54        let ruby_pkg = e2e_config.resolve_package("ruby");
55        let gem_name = ruby_pkg
56            .as_ref()
57            .and_then(|p| p.name.as_ref())
58            .cloned()
59            .unwrap_or_else(|| config.name.replace('-', "_"));
60        let gem_path = ruby_pkg
61            .as_ref()
62            .and_then(|p| p.path.as_ref())
63            .cloned()
64            .unwrap_or_else(|| "../../packages/ruby".to_string());
65        let gem_version = ruby_pkg
66            .as_ref()
67            .and_then(|p| p.version.as_ref())
68            .cloned()
69            .or_else(|| config.resolved_version())
70            .unwrap_or_else(|| "0.1.0".to_string());
71
72        // Generate Gemfile.
73        files.push(GeneratedFile {
74            path: output_base.join("Gemfile"),
75            content: render_gemfile(&gem_name, &gem_path, &gem_version, e2e_config.dep_mode),
76            generated_header: false,
77        });
78
79        // Generate .rubocop.yaml for linting generated specs.
80        files.push(GeneratedFile {
81            path: output_base.join(".rubocop.yaml"),
82            content: render_rubocop_yaml(),
83            generated_header: false,
84        });
85
86        // Check if any fixture is an HTTP test (needs mock server bootstrap).
87        let has_http_fixtures = groups
88            .iter()
89            .flat_map(|g| g.fixtures.iter())
90            .any(|f| f.needs_mock_server());
91
92        // Check if any fixture uses file_path or bytes args (needs chdir to test_documents).
93        let has_file_fixtures = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| {
94            let cc = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
95            cc.args
96                .iter()
97                .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
98        });
99
100        // Always generate spec/spec_helper.rb when file-based or HTTP fixtures are present.
101        if has_file_fixtures || has_http_fixtures {
102            files.push(GeneratedFile {
103                path: output_base.join("spec").join("spec_helper.rb"),
104                content: render_spec_helper(
105                    has_file_fixtures,
106                    has_http_fixtures,
107                    &e2e_config.test_documents_relative_from(1),
108                ),
109                generated_header: true,
110            });
111        }
112
113        // Generate spec files per category.
114        let spec_base = output_base.join("spec");
115
116        for group in groups {
117            let active: Vec<&Fixture> = group
118                .fixtures
119                .iter()
120                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
121                .collect();
122
123            if active.is_empty() {
124                continue;
125            }
126
127            let field_resolver_pre = FieldResolver::new(
128                &e2e_config.fields,
129                &e2e_config.fields_optional,
130                &e2e_config.result_fields,
131                &e2e_config.fields_array,
132                &std::collections::HashSet::new(),
133            );
134            // Skip the entire file if no fixture in this category produces output.
135            let has_any_output = active.iter().any(|f| {
136                // HTTP tests always produce output.
137                if f.is_http_test() {
138                    return true;
139                }
140                let expects_error = f.assertions.iter().any(|a| a.assertion_type == "error");
141                let has_not_error = f.assertions.iter().any(|a| a.assertion_type == "not_error");
142                expects_error || has_not_error || has_usable_assertion(f, &field_resolver_pre, result_is_simple)
143            });
144            if !has_any_output {
145                continue;
146            }
147
148            let filename = format!("{}_spec.rb", sanitize_filename(&group.category));
149            let field_resolver = FieldResolver::new(
150                &e2e_config.fields,
151                &e2e_config.fields_optional,
152                &e2e_config.result_fields,
153                &e2e_config.fields_array,
154                &std::collections::HashSet::new(),
155            );
156            let content = render_spec_file(
157                &group.category,
158                &active,
159                &module_path,
160                class_name.as_deref(),
161                &gem_name,
162                &field_resolver,
163                options_type.as_deref(),
164                enum_fields,
165                result_is_simple,
166                e2e_config,
167                has_file_fixtures || has_http_fixtures,
168            );
169            files.push(GeneratedFile {
170                path: spec_base.join(filename),
171                content,
172                generated_header: true,
173            });
174        }
175
176        Ok(files)
177    }
178
179    fn language_name(&self) -> &'static str {
180        "ruby"
181    }
182}
183
184// ---------------------------------------------------------------------------
185// Rendering
186// ---------------------------------------------------------------------------
187
188fn render_gemfile(
189    gem_name: &str,
190    gem_path: &str,
191    gem_version: &str,
192    dep_mode: crate::config::DependencyMode,
193) -> String {
194    let gem_line = match dep_mode {
195        crate::config::DependencyMode::Registry => format!("gem '{gem_name}', '{gem_version}'"),
196        crate::config::DependencyMode::Local => format!("gem '{gem_name}', path: '{gem_path}'"),
197    };
198    crate::template_env::render(
199        "ruby/Gemfile.jinja",
200        minijinja::context! {
201            gem_line => gem_line,
202            rspec => tv::gem::RSPEC_E2E,
203            rubocop => tv::gem::RUBOCOP_E2E,
204            rubocop_rspec => tv::gem::RUBOCOP_RSPEC_E2E,
205            faraday => tv::gem::FARADAY,
206        },
207    )
208}
209
210fn render_spec_helper(has_file_fixtures: bool, has_http_fixtures: bool, test_documents_path: &str) -> String {
211    let header = hash::header(CommentStyle::Hash);
212    let mut out = header;
213    out.push_str("# frozen_string_literal: true\n");
214
215    if has_file_fixtures {
216        let _ = writeln!(out);
217        let _ = writeln!(
218            out,
219            "# Change to the configured test-documents directory so that fixture file paths like"
220        );
221        let _ = writeln!(
222            out,
223            "# \"pdf/fake_memo.pdf\" resolve correctly when running rspec from e2e/ruby/."
224        );
225        let _ = writeln!(
226            out,
227            "# spec_helper.rb lives in e2e/ruby/spec/; the fixtures dir resolves three directories up."
228        );
229        let _ = writeln!(
230            out,
231            "_test_documents = File.expand_path('{test_documents_path}', __dir__)"
232        );
233        let _ = writeln!(out, "Dir.chdir(_test_documents) if Dir.exist?(_test_documents)");
234    }
235
236    if has_http_fixtures {
237        out.push_str(
238            r#"
239require 'json'
240require 'open3'
241
242# Spawn the mock-server binary and set MOCK_SERVER_URL for all tests.
243RSpec.configure do |config|
244  config.before(:suite) do
245    bin = File.expand_path('../../rust/target/release/mock-server', __dir__)
246    fixtures_dir = File.expand_path('../../../fixtures', __dir__)
247    unless File.exist?(bin)
248      warn "mock-server binary not found at #{bin} — run: cargo build --manifest-path e2e/rust/Cargo.toml --bin mock-server --release"
249    end
250    stdin, stdout, _stderr, _wait = Open3.popen3(bin, fixtures_dir)
251    # Read startup lines: MOCK_SERVER_URL= then optional MOCK_SERVERS=.
252    url = nil
253    8.times do
254      line = stdout.readline.strip rescue break
255      if line.start_with?('MOCK_SERVER_URL=')
256        url = line.split('=', 2).last
257        ENV['MOCK_SERVER_URL'] = url
258      elsif line.start_with?('MOCK_SERVERS=')
259        json_val = line.split('=', 2).last
260        ENV['MOCK_SERVERS'] = json_val
261        JSON.parse(json_val).each do |fid, furl|
262          ENV["MOCK_SERVER_#{fid.upcase}"] = furl
263        end
264        break
265      elsif url
266        break
267      end
268    end
269    # Drain stdout in background.
270    Thread.new { stdout.read }
271    # Store stdin so we can close it on teardown.
272    @_mock_server_stdin = stdin
273  end
274
275  config.after(:suite) do
276    @_mock_server_stdin&.close
277  end
278end
279"#,
280        );
281    }
282
283    out
284}
285
286fn render_rubocop_yaml() -> String {
287    crate::template_env::render("ruby/rubocop.yml.jinja", minijinja::context! {})
288}
289
290#[allow(clippy::too_many_arguments)]
291fn render_spec_file(
292    category: &str,
293    fixtures: &[&Fixture],
294    module_path: &str,
295    class_name: Option<&str>,
296    gem_name: &str,
297    field_resolver: &FieldResolver,
298    options_type: Option<&str>,
299    enum_fields: &HashMap<String, String>,
300    result_is_simple: bool,
301    e2e_config: &E2eConfig,
302    needs_spec_helper: bool,
303) -> String {
304    // Resolve client_factory from ruby override.
305    let client_factory = e2e_config
306        .call
307        .overrides
308        .get("ruby")
309        .and_then(|o| o.client_factory.as_deref());
310
311    // Build requires list
312    let require_name = if module_path.is_empty() { gem_name } else { module_path };
313    let mut requires = vec![require_name.replace('-', "_"), "json".to_string()];
314
315    let has_http = fixtures.iter().any(|f| f.is_http_test());
316    if needs_spec_helper || has_http {
317        requires.push("spec_helper".to_string());
318    }
319
320    // Build the Ruby module/class qualifier for calls.
321    let call_receiver = class_name
322        .map(|s| s.to_string())
323        .unwrap_or_else(|| ruby_module_name(module_path));
324
325    // Check for array contains assertions
326    let has_array_contains = fixtures.iter().any(|fixture| {
327        fixture.assertions.iter().any(|a| {
328            matches!(a.assertion_type.as_str(), "contains" | "contains_all" | "not_contains")
329                && a.field
330                    .as_deref()
331                    .is_some_and(|f| !f.is_empty() && field_resolver.is_array(field_resolver.resolve(f)))
332        })
333    });
334
335    // Build examples
336    let mut examples = Vec::new();
337    for fixture in fixtures {
338        if fixture.http.is_some() {
339            // HTTP example is handled separately (uses shared driver)
340            let mut out = String::new();
341            render_http_example(&mut out, fixture);
342            examples.push(out);
343        } else {
344            // Resolve per-fixture call config so we can detect streaming up front.
345            let fixture_call = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
346            let fixture_call_overrides = fixture_call.overrides.get("ruby");
347            let raw_function_name = fixture_call_overrides
348                .and_then(|o| o.function.as_ref())
349                .cloned()
350                .unwrap_or_else(|| fixture_call.function.clone());
351
352            let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
353            let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
354            let is_streaming = raw_function_name == "chat_stream";
355
356            // Non-HTTP, non-streaming fixtures with no usable assertions stay pending.
357            if !expects_error && !has_usable && !is_streaming {
358                let test_name = sanitize_ident(&fixture.id);
359                let description = fixture.description.replace('\'', "\\'");
360                let mut out = String::new();
361                out.push_str(&format!("  it '{test_name}: {description}' do\n"));
362                out.push_str("    skip 'Non-HTTP fixture cannot be tested via Net::HTTP'\n");
363                out.push_str("  end\n");
364                examples.push(out);
365            } else {
366                // Streaming methods do not take the `_async` suffix — Magnus emits
367                // `chat_stream` as a block-yielding method. All other async Rust
368                // methods are bound with the `_async` suffix.
369                let fixture_function_name = if is_streaming {
370                    raw_function_name
371                } else if fixture_call.r#async && !raw_function_name.ends_with("_async") {
372                    format!("{raw_function_name}_async")
373                } else {
374                    raw_function_name
375                };
376                let fixture_result_var = &fixture_call.result_var;
377                let fixture_args = &fixture_call.args;
378                let fixture_client_factory = fixture_call_overrides
379                    .and_then(|o| o.client_factory.as_deref())
380                    .or(client_factory);
381                let fixture_options_type = fixture_call_overrides
382                    .and_then(|o| o.options_type.as_deref())
383                    .or(options_type);
384
385                let fixture_extra_args: Vec<String> =
386                    fixture_call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
387                // Use per-fixture-call result_is_simple so per-call overrides like
388                // `speech` (returns bytes) take precedence over the top-level call default.
389                let fixture_result_is_simple =
390                    fixture_call.result_is_simple || fixture_call_overrides.is_some_and(|o| o.result_is_simple);
391                // Per-call enum_fields take precedence — e.g. `[crates.e2e.calls.create_batch.overrides.ruby] enum_fields`
392                // labels `status = "BatchStatus"` for the batch lifecycle, but the global
393                // `[crates.e2e.call.overrides.ruby]` map only carries chat-shape entries.
394                let fixture_enum_fields: &HashMap<String, String> =
395                    fixture_call_overrides.map(|o| &o.enum_fields).unwrap_or(enum_fields);
396                let example = if is_streaming {
397                    render_chat_stream_example(
398                        fixture,
399                        &fixture_function_name,
400                        &call_receiver,
401                        fixture_args,
402                        fixture_options_type,
403                        fixture_enum_fields,
404                        e2e_config,
405                        fixture_client_factory,
406                        &fixture_extra_args,
407                    )
408                } else {
409                    render_example(
410                        fixture,
411                        &fixture_function_name,
412                        &call_receiver,
413                        fixture_result_var,
414                        fixture_args,
415                        field_resolver,
416                        fixture_options_type,
417                        fixture_enum_fields,
418                        fixture_result_is_simple,
419                        e2e_config,
420                        fixture_client_factory,
421                        &fixture_extra_args,
422                    )
423                };
424                examples.push(example);
425            }
426        }
427    }
428
429    let header = hash::header(CommentStyle::Hash);
430    crate::template_env::render(
431        "ruby/test_file.jinja",
432        minijinja::context! {
433            category => category,
434            requires => requires,
435            has_array_contains => has_array_contains,
436            has_http => has_http,
437            examples => examples,
438            header => header,
439        },
440    )
441}
442
443/// Check if a fixture has at least one assertion that will produce an executable
444/// expect() call (not just a skip comment).
445fn has_usable_assertion(fixture: &Fixture, field_resolver: &FieldResolver, result_is_simple: bool) -> bool {
446    fixture.assertions.iter().any(|a| {
447        // not_error is implicit (call succeeding), error is handled separately.
448        if a.assertion_type == "not_error" || a.assertion_type == "error" {
449            return false;
450        }
451        // Check field validity.
452        if let Some(f) = &a.field {
453            if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
454                return false;
455            }
456            // When result_is_simple, skip non-content fields.
457            if result_is_simple {
458                let f_lower = f.to_lowercase();
459                if !f.is_empty()
460                    && f_lower != "content"
461                    && (f_lower.starts_with("metadata")
462                        || f_lower.starts_with("document")
463                        || f_lower.starts_with("structure"))
464                {
465                    return false;
466                }
467            }
468        }
469        true
470    })
471}
472
473// ---------------------------------------------------------------------------
474// HTTP test rendering — shared-driver integration
475// ---------------------------------------------------------------------------
476
477/// Thin renderer that emits RSpec `describe` + `it` blocks targeting a mock server
478/// via `Net::HTTP`. Satisfies [`client::TestClientRenderer`] so the shared
479/// [`client::http_call::render_http_test`] driver drives the call sequence.
480struct RubyTestClientRenderer;
481
482impl client::TestClientRenderer for RubyTestClientRenderer {
483    fn language_name(&self) -> &'static str {
484        "ruby"
485    }
486
487    /// Emit `describe '{fn_name}' do` + inner `it '{description}' do`.
488    ///
489    /// `fn_name` is the sanitised fixture id used as the describe label.
490    /// When `skip_reason` is `Some`, the inner `it` block gets a `skip` call so
491    /// the shared driver short-circuits before emitting any assertions.
492    fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
493        let escaped_description = description.replace('\'', "\\'");
494        let rendered = crate::template_env::render(
495            "ruby/http_test.jinja",
496            minijinja::context! {
497                fn_name => fn_name,
498                description => escaped_description,
499                skip_reason => skip_reason,
500            },
501        );
502        out.push_str(&rendered);
503    }
504
505    /// Close the inner `it` block and the outer `describe` block.
506    fn render_test_close(&self, out: &mut String) {
507        let rendered = crate::template_env::render("ruby/http_test_close.jinja", minijinja::context! {});
508        out.push_str(&rendered);
509    }
510
511    /// Emit a `Net::HTTP` request to the mock server using the path from `ctx`.
512    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
513        let method = ctx.method.to_uppercase();
514        let method_class = http_method_class(&method);
515
516        let has_body = ctx
517            .body
518            .is_some_and(|b| !matches!(b, serde_json::Value::String(s) if s.is_empty()));
519
520        let ruby_body = if has_body {
521            json_to_ruby(ctx.body.unwrap())
522        } else {
523            String::new()
524        };
525
526        let headers: Vec<minijinja::Value> = ctx
527            .headers
528            .iter()
529            .filter(|(k, _)| {
530                // Skip Content-Type when already set from the body above.
531                !(has_body && k.to_lowercase() == "content-type")
532            })
533            .map(|(k, v)| {
534                minijinja::context! {
535                    key_literal => ruby_string_literal(k),
536                    value_literal => ruby_string_literal(v),
537                }
538            })
539            .collect();
540
541        let rendered = crate::template_env::render(
542            "ruby/http_request.jinja",
543            minijinja::context! {
544                method_class => method_class,
545                path => ctx.path,
546                has_body => has_body,
547                ruby_body => ruby_body,
548                headers => headers,
549                response_var => ctx.response_var,
550            },
551        );
552        out.push_str(&rendered);
553    }
554
555    /// Emit `expect(response.code.to_i).to eq(status)`.
556    ///
557    /// Net::HTTP returns the HTTP status as a `String`; `.to_i` converts it for
558    /// comparison with the integer literal from the fixture.
559    fn render_assert_status(&self, out: &mut String, response_var: &str, status: u16) {
560        out.push_str(&format!("      expect({response_var}.code.to_i).to eq({status})\n"));
561    }
562
563    /// Emit a header assertion using `response[header_key]`.
564    ///
565    /// Handles the three special tokens: `<<present>>`, `<<absent>>`, `<<uuid>>`.
566    fn render_assert_header(&self, out: &mut String, response_var: &str, name: &str, expected: &str) {
567        let header_key = name.to_lowercase();
568        let header_expr = format!("{response_var}[{}]", ruby_string_literal(&header_key));
569        let assertion = match expected {
570            "<<present>>" => {
571                format!("      expect({header_expr}).not_to be_nil\n")
572            }
573            "<<absent>>" => {
574                format!("      expect({header_expr}).to be_nil\n")
575            }
576            "<<uuid>>" => {
577                format!(
578                    "      expect({header_expr}).to match(/\\A[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}\\z/i)\n"
579                )
580            }
581            literal => {
582                let ruby_val = ruby_string_literal(literal);
583                format!("      expect({header_expr}).to eq({ruby_val})\n")
584            }
585        };
586        out.push_str(&assertion);
587    }
588
589    /// Emit a full JSON body equality assertion.
590    ///
591    /// Plain string bodies are compared as raw text; structured bodies are parsed
592    /// with `JSON.parse` and compared as Ruby Hash/Array values.
593    fn render_assert_json_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
594        match expected {
595            serde_json::Value::String(s) => {
596                let ruby_val = ruby_string_literal(s);
597                out.push_str(&format!("      expect({response_var}.body).to eq({ruby_val})\n"));
598            }
599            _ => {
600                let ruby_val = json_to_ruby(expected);
601                out.push_str(&format!(
602                    "      _body = {response_var}.body && !{response_var}.body.empty? ? JSON.parse({response_var}.body) : nil\n"
603                ));
604                out.push_str(&format!("      expect(_body).to eq({ruby_val})\n"));
605            }
606        }
607    }
608
609    /// Emit partial body assertions: one `expect(_body[key]).to eq(val)` per field.
610    fn render_assert_partial_body(&self, out: &mut String, response_var: &str, expected: &serde_json::Value) {
611        if let Some(obj) = expected.as_object() {
612            out.push_str(&format!("      _body = JSON.parse({response_var}.body)\n"));
613            for (key, val) in obj {
614                let ruby_key = ruby_string_literal(key);
615                let ruby_val = json_to_ruby(val);
616                out.push_str(&format!("      expect(_body[{ruby_key}]).to eq({ruby_val})\n"));
617            }
618        }
619    }
620
621    /// Emit validation-error assertions, checking each expected `msg` against the
622    /// parsed body's `errors` array.
623    fn render_assert_validation_errors(
624        &self,
625        out: &mut String,
626        response_var: &str,
627        errors: &[ValidationErrorExpectation],
628    ) {
629        for err in errors {
630            let msg_lit = ruby_string_literal(&err.msg);
631            out.push_str(&format!("      _body = JSON.parse({response_var}.body)\n"));
632            out.push_str("      _errors = _body['errors'] || []\n");
633            out.push_str(&format!(
634                "      expect(_errors.map {{ |e| e['msg'] }}).to include({msg_lit})\n"
635            ));
636        }
637    }
638}
639
640/// Render an RSpec example for an HTTP server test fixture via the shared driver.
641///
642/// Delegates to [`client::http_call::render_http_test`] after handling the one
643/// Ruby-specific pre-condition: HTTP 101 (WebSocket upgrade) cannot be exercised
644/// via `Net::HTTP` and is emitted as a pending `it` block directly.
645fn render_http_example(out: &mut String, fixture: &Fixture) {
646    // HTTP 101 (WebSocket upgrade) cannot be tested via Net::HTTP.
647    // Emit the skip block directly rather than pushing a skip directive through
648    // the shared driver, which would require a full `fixture.skip` entry.
649    if fixture
650        .http
651        .as_ref()
652        .is_some_and(|h| h.expected_response.status_code == 101)
653    {
654        if let Some(http) = fixture.http.as_ref() {
655            let description = fixture.description.replace('\'', "\\'");
656            let method = http.request.method.to_uppercase();
657            let path = &http.request.path;
658            let rendered = crate::template_env::render(
659                "ruby/http_101_skip.jinja",
660                minijinja::context! {
661                    method => method,
662                    path => path,
663                    description => description,
664                },
665            );
666            out.push_str(&rendered);
667        }
668        return;
669    }
670
671    client::http_call::render_http_test(out, &RubyTestClientRenderer, fixture);
672}
673
674/// Convert an uppercase HTTP method string to Ruby's Net::HTTP class name.
675/// Ruby uses title-cased names: Get, Post, Put, Delete, Patch, Head, Options, Trace.
676fn http_method_class(method: &str) -> String {
677    let mut chars = method.chars();
678    match chars.next() {
679        None => String::new(),
680        Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
681    }
682}
683
684// ---------------------------------------------------------------------------
685// Chat-stream test rendering — block iteration with local aggregation
686// ---------------------------------------------------------------------------
687
688/// Render an RSpec example for a `chat_stream` fixture.
689///
690/// The Ruby binding's `chat_stream` is block-yielding: each yielded value is a
691/// `LiterLlm::ChatCompletionChunk`. The codegen builds local aggregator vars
692/// (`chunks`, `stream_content`, `stream_complete`, plus optional
693/// `last_finish_reason`, `tool_calls_json`, `total_tokens`) inside the block and
694/// then emits assertions on those locals — never on response pseudo-fields.
695#[allow(clippy::too_many_arguments)]
696fn render_chat_stream_example(
697    fixture: &Fixture,
698    function_name: &str,
699    call_receiver: &str,
700    args: &[crate::config::ArgMapping],
701    options_type: Option<&str>,
702    enum_fields: &HashMap<String, String>,
703    e2e_config: &E2eConfig,
704    client_factory: Option<&str>,
705    extra_args: &[String],
706) -> String {
707    let test_name = sanitize_ident(&fixture.id);
708    let description = fixture.description.replace('\'', "\\'");
709    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
710    let fixture_id = fixture.id.clone();
711
712    let (mut setup_lines, args_str) = build_args_and_setup(
713        &fixture.input,
714        args,
715        call_receiver,
716        options_type,
717        enum_fields,
718        false,
719        fixture,
720    );
721
722    let mut final_args = args_str;
723    if !extra_args.is_empty() {
724        let extra_str = extra_args.join(", ");
725        if final_args.is_empty() {
726            final_args = extra_str;
727        } else {
728            final_args = format!("{final_args}, {extra_str}");
729        }
730    }
731
732    // Detect which aggregators a fixture's assertions actually need so we don't
733    // emit unused locals (rubocop trips on assigned-but-unread vars).
734    let mut needs_finish_reason = false;
735    let mut needs_tool_calls_json = false;
736    let mut needs_tool_calls_0_function_name = false;
737    let mut needs_total_tokens = false;
738    for a in &fixture.assertions {
739        if let Some(f) = a.field.as_deref() {
740            match f {
741                "finish_reason" => needs_finish_reason = true,
742                "tool_calls" => needs_tool_calls_json = true,
743                "tool_calls[0].function.name" => needs_tool_calls_0_function_name = true,
744                "usage.total_tokens" => needs_total_tokens = true,
745                _ => {}
746            }
747        }
748    }
749
750    let mut out = String::new();
751    out.push_str(&format!("  it '{test_name}: {description}' do\n"));
752
753    // Client construction.
754    let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
755    let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
756    if let Some(cf) = client_factory {
757        if has_mock {
758            let base_url_expr = if fixture.has_host_root_route() {
759                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
760                format!("(ENV.fetch('{env_key}', nil) || ENV.fetch('MOCK_SERVER_URL') + '/fixtures/{fixture_id}')")
761            } else {
762                format!("ENV.fetch('MOCK_SERVER_URL') + '/fixtures/{fixture_id}'")
763            };
764            out.push_str(&format!(
765                "    client = {call_receiver}.{cf}('test-key', {base_url_expr})\n"
766            ));
767        } else if let Some(key_var) = api_key_var {
768            out.push_str(&format!("    api_key = ENV['{key_var}']\n"));
769            out.push_str(&format!("    skip '{key_var} not set' unless api_key\n"));
770            out.push_str(&format!("    client = {call_receiver}.{cf}(api_key)\n"));
771        } else {
772            out.push_str(&format!("    client = {call_receiver}.{cf}('test-key')\n"));
773        }
774    }
775
776    // Visitor (rare for streaming, but support it for parity).
777    if let Some(visitor_spec) = &fixture.visitor {
778        let _ = build_ruby_visitor(&mut setup_lines, visitor_spec);
779    }
780    for line in &setup_lines {
781        out.push_str(&format!("    {line}\n"));
782    }
783
784    let call_expr = if client_factory.is_some() {
785        format!("client.{function_name}({final_args})")
786    } else {
787        format!("{call_receiver}.{function_name}({final_args})")
788    };
789
790    if expects_error {
791        out.push_str(&format!("    expect {{ {call_expr} {{ |_chunk| }} }}.to raise_error\n"));
792        out.push_str("  end\n");
793        return out;
794    }
795
796    // Build aggregators inside a block so the iterator drives the stream synchronously.
797    out.push_str("    chunks = []\n");
798    out.push_str("    stream_content = ''.dup\n");
799    out.push_str("    stream_complete = false\n");
800    if needs_finish_reason {
801        out.push_str("    last_finish_reason = nil\n");
802    }
803    if needs_tool_calls_json {
804        out.push_str("    tool_calls_json = nil\n");
805    }
806    if needs_tool_calls_0_function_name {
807        out.push_str("    tool_calls_0_function_name = nil\n");
808    }
809    if needs_total_tokens {
810        out.push_str("    total_tokens = nil\n");
811    }
812    out.push_str(&format!("    {call_expr} do |chunk|\n"));
813    out.push_str("      chunks << chunk\n");
814    out.push_str("      choice = chunk.choices && chunk.choices[0]\n");
815    out.push_str("      if choice\n");
816    out.push_str("        delta = choice.delta\n");
817    out.push_str("        if delta && delta.content\n");
818    out.push_str("          stream_content << delta.content\n");
819    out.push_str("        end\n");
820    if needs_finish_reason {
821        out.push_str("        if choice.finish_reason\n");
822        out.push_str("          last_finish_reason = choice.finish_reason.to_s\n");
823        out.push_str("        end\n");
824    }
825    if needs_tool_calls_json || needs_tool_calls_0_function_name {
826        out.push_str("        tcs = delta && delta.tool_calls\n");
827        out.push_str("        if tcs && !tcs.empty?\n");
828        if needs_tool_calls_json {
829            out.push_str(
830                "          tool_calls_json ||= tcs.map { |tc| { 'function' => { 'name' => (tc.function && tc.function.name rescue nil) } } }.to_json\n",
831            );
832        }
833        if needs_tool_calls_0_function_name {
834            out.push_str(
835                "          tool_calls_0_function_name ||= (tcs[0].function && tcs[0].function.name rescue nil)\n",
836            );
837        }
838        out.push_str("        end\n");
839    }
840    out.push_str("      end\n");
841    if needs_total_tokens {
842        out.push_str("      if chunk.usage && chunk.usage.total_tokens\n");
843        out.push_str("        total_tokens = chunk.usage.total_tokens\n");
844        out.push_str("      end\n");
845    }
846    out.push_str("    end\n");
847    out.push_str("    stream_complete = true\n");
848
849    // Render assertions on the local aggregator vars.
850    for assertion in &fixture.assertions {
851        emit_chat_stream_assertion(&mut out, assertion, e2e_config);
852    }
853
854    // Always assert that the stream completed cleanly so non-empty test bodies
855    // are guaranteed by RSpec's at-least-one-expectation requirement.
856    if !fixture
857        .assertions
858        .iter()
859        .any(|a| a.field.as_deref() == Some("stream_complete"))
860    {
861        out.push_str("    expect(stream_complete).to be(true)\n");
862    }
863
864    out.push_str("  end\n");
865    out
866}
867
868/// Map a streaming fixture assertion to an `expect` call on the local aggregator
869/// variable produced by [`render_chat_stream_example`]. Pseudo-fields like
870/// `chunks` / `stream_content` / `stream_complete` resolve to the in-block locals,
871/// not response accessors.
872fn emit_chat_stream_assertion(out: &mut String, assertion: &Assertion, _e2e_config: &E2eConfig) {
873    let atype = assertion.assertion_type.as_str();
874    if atype == "not_error" || atype == "error" {
875        return;
876    }
877    let field = assertion.field.as_deref().unwrap_or("");
878
879    enum Kind {
880        Chunks,
881        Bool,
882        Str,
883        IntTokens,
884        Json,
885        Unsupported,
886    }
887
888    let (expr, kind) = match field {
889        "chunks" => ("chunks", Kind::Chunks),
890        "stream_content" => ("stream_content", Kind::Str),
891        "stream_complete" => ("stream_complete", Kind::Bool),
892        "no_chunks_after_done" => ("stream_complete", Kind::Bool),
893        "finish_reason" => ("last_finish_reason", Kind::Str),
894        "tool_calls" => ("tool_calls_json", Kind::Json),
895        "tool_calls[0].function.name" => ("tool_calls_0_function_name", Kind::Str),
896        "usage.total_tokens" => ("total_tokens", Kind::IntTokens),
897        _ => ("", Kind::Unsupported),
898    };
899
900    if matches!(kind, Kind::Unsupported) {
901        out.push_str(&format!(
902            "    # skipped: streaming assertion on unsupported field '{field}'\n"
903        ));
904        return;
905    }
906
907    match (atype, &kind) {
908        ("count_min", Kind::Chunks) => {
909            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
910                out.push_str(&format!("    expect({expr}.length).to be >= {n}\n"));
911            }
912        }
913        ("count_equals", Kind::Chunks) => {
914            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
915                out.push_str(&format!("    expect({expr}.length).to eq({n})\n"));
916            }
917        }
918        ("equals", Kind::Str) => {
919            if let Some(val) = &assertion.value {
920                let rb_val = json_to_ruby(val);
921                out.push_str(&format!("    expect({expr}.to_s).to eq({rb_val})\n"));
922            }
923        }
924        ("contains", Kind::Str) => {
925            if let Some(val) = &assertion.value {
926                let rb_val = json_to_ruby(val);
927                out.push_str(&format!("    expect({expr}.to_s).to include({rb_val})\n"));
928            }
929        }
930        ("not_empty", Kind::Str) => {
931            out.push_str(&format!("    expect({expr}.to_s).not_to be_empty\n"));
932        }
933        ("not_empty", Kind::Json) => {
934            out.push_str(&format!("    expect({expr}).not_to be_nil\n"));
935        }
936        ("is_empty", Kind::Str) => {
937            out.push_str(&format!("    expect({expr}.to_s).to be_empty\n"));
938        }
939        ("is_true", Kind::Bool) => {
940            out.push_str(&format!("    expect({expr}).to be(true)\n"));
941        }
942        ("is_false", Kind::Bool) => {
943            out.push_str(&format!("    expect({expr}).to be(false)\n"));
944        }
945        ("greater_than_or_equal", Kind::IntTokens) => {
946            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
947                out.push_str(&format!("    expect({expr}).to be >= {n}\n"));
948            }
949        }
950        ("equals", Kind::IntTokens) => {
951            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
952                out.push_str(&format!("    expect({expr}).to eq({n})\n"));
953            }
954        }
955        _ => {
956            out.push_str(&format!(
957                "    # skipped: streaming assertion '{atype}' on field '{field}' not supported\n"
958            ));
959        }
960    }
961}
962
963// ---------------------------------------------------------------------------
964// Function-call test rendering
965// ---------------------------------------------------------------------------
966
967#[allow(clippy::too_many_arguments)]
968fn render_example(
969    fixture: &Fixture,
970    function_name: &str,
971    call_receiver: &str,
972    result_var: &str,
973    args: &[crate::config::ArgMapping],
974    field_resolver: &FieldResolver,
975    options_type: Option<&str>,
976    enum_fields: &HashMap<String, String>,
977    result_is_simple: bool,
978    e2e_config: &E2eConfig,
979    client_factory: Option<&str>,
980    extra_args: &[String],
981) -> String {
982    let test_name = sanitize_ident(&fixture.id);
983    let description = fixture.description.replace('\'', "\\'");
984    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
985    let fixture_id = fixture.id.clone();
986
987    let (mut setup_lines, args_str) = build_args_and_setup(
988        &fixture.input,
989        args,
990        call_receiver,
991        options_type,
992        enum_fields,
993        result_is_simple,
994        fixture,
995    );
996
997    // Build visitor if present and add to setup
998    let mut visitor_arg = String::new();
999    if let Some(visitor_spec) = &fixture.visitor {
1000        visitor_arg = build_ruby_visitor(&mut setup_lines, visitor_spec);
1001    }
1002
1003    let mut final_args = if visitor_arg.is_empty() {
1004        args_str
1005    } else if args_str.is_empty() {
1006        visitor_arg
1007    } else {
1008        format!("{args_str}, {visitor_arg}")
1009    };
1010
1011    // Append per-fixture extra_args (e.g. trailing `nil` for `list_files(purpose)`).
1012    if !extra_args.is_empty() {
1013        let extra_str = extra_args.join(", ");
1014        if final_args.is_empty() {
1015            final_args = extra_str;
1016        } else {
1017            final_args = format!("{final_args}, {extra_str}");
1018        }
1019    }
1020
1021    // When client_factory is configured, create a client instance and call methods on it.
1022    let call_expr = if client_factory.is_some() {
1023        format!("client.{function_name}({final_args})")
1024    } else {
1025        format!("{call_receiver}.{function_name}({final_args})")
1026    };
1027
1028    // Check if any non-error assertion actually uses the result variable.
1029    let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
1030
1031    // Render all assertions upfront into a string
1032    let mut assertions_rendered = String::new();
1033    for assertion in &fixture.assertions {
1034        render_assertion(
1035            &mut assertions_rendered,
1036            assertion,
1037            result_var,
1038            field_resolver,
1039            result_is_simple,
1040            e2e_config,
1041            enum_fields,
1042        );
1043    }
1044
1045    let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
1046    let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
1047    crate::template_env::render(
1048        "ruby/test_function.jinja",
1049        minijinja::context! {
1050            test_name => test_name,
1051            description => description,
1052            expects_error => expects_error,
1053            setup_lines => setup_lines,
1054            call_expr => call_expr,
1055            result_var => result_var,
1056            assertions_rendered => assertions_rendered,
1057            has_usable => has_usable,
1058            client_factory => client_factory,
1059            fixture_id => fixture_id,
1060            call_receiver => call_receiver,
1061            has_mock => has_mock,
1062            api_key_var => api_key_var,
1063        },
1064    )
1065}
1066
1067/// Build setup lines (e.g. handle creation) and the argument list for the function call.
1068///
1069/// Returns `(setup_lines, args_string)`.
1070/// Emit Ruby batch item constructors for BatchBytesItem or BatchFileItem arrays.
1071fn emit_ruby_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
1072    if let Some(items) = arr.as_array() {
1073        let item_strs: Vec<String> = items
1074            .iter()
1075            .filter_map(|item| {
1076                if let Some(obj) = item.as_object() {
1077                    match elem_type {
1078                        "BatchBytesItem" => {
1079                            let content = obj.get("content").and_then(|v| v.as_array());
1080                            let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1081                            let config = obj.get("config");
1082                            let content_code = if let Some(arr) = content {
1083                                let bytes: Vec<String> =
1084                                    arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
1085                                // Pass as Ruby array - Magnus will convert Array<u8> to Vec<u8>
1086                                format!("[{}]", bytes.join(", "))
1087                            } else {
1088                                "[]".to_string()
1089                            };
1090                            let config_arg = if let Some(cfg) = config {
1091                                if cfg.is_null() {
1092                                    "nil".to_string()
1093                                } else {
1094                                    json_to_ruby(cfg)
1095                                }
1096                            } else {
1097                                "nil".to_string()
1098                            };
1099                            Some(format!(
1100                                "Kreuzberg::{}.new(content: {}, mime_type: \"{}\", config: {})",
1101                                elem_type, content_code, mime_type, config_arg
1102                            ))
1103                        }
1104                        "BatchFileItem" => {
1105                            let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1106                            let config = obj.get("config");
1107                            let config_arg = if let Some(cfg) = config {
1108                                if cfg.is_null() {
1109                                    "nil".to_string()
1110                                } else {
1111                                    json_to_ruby(cfg)
1112                                }
1113                            } else {
1114                                "nil".to_string()
1115                            };
1116                            Some(format!(
1117                                "Kreuzberg::{}.new(path: \"{}\", config: {})",
1118                                elem_type, path, config_arg
1119                            ))
1120                        }
1121                        _ => None,
1122                    }
1123                } else {
1124                    None
1125                }
1126            })
1127            .collect();
1128        format!("[{}]", item_strs.join(", "))
1129    } else {
1130        "[]".to_string()
1131    }
1132}
1133
1134fn build_args_and_setup(
1135    input: &serde_json::Value,
1136    args: &[crate::config::ArgMapping],
1137    call_receiver: &str,
1138    options_type: Option<&str>,
1139    enum_fields: &HashMap<String, String>,
1140    result_is_simple: bool,
1141    fixture: &crate::fixture::Fixture,
1142) -> (Vec<String>, String) {
1143    let fixture_id = &fixture.id;
1144    if args.is_empty() {
1145        // No args config: pass the whole input only when it's non-empty.
1146        // Functions with no parameters have empty input and must be called
1147        // with no arguments — not with `{}` or `nil`.
1148        let is_empty_input = match input {
1149            serde_json::Value::Null => true,
1150            serde_json::Value::Object(m) => m.is_empty(),
1151            _ => false,
1152        };
1153        if is_empty_input {
1154            return (Vec::new(), String::new());
1155        }
1156        return (Vec::new(), json_to_ruby(input));
1157    }
1158
1159    let mut setup_lines: Vec<String> = Vec::new();
1160    let mut parts: Vec<String> = Vec::new();
1161    // Track optional args that were skipped; if a later arg is emitted we must back-fill nil
1162    // to preserve positional correctness (e.g. extract_file(path, nil, config)).
1163    let mut skipped_optional_count: usize = 0;
1164
1165    for arg in args {
1166        if arg.arg_type == "mock_url" {
1167            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1168            for _ in 0..skipped_optional_count {
1169                parts.push("nil".to_string());
1170            }
1171            skipped_optional_count = 0;
1172            if fixture.has_host_root_route() {
1173                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1174                setup_lines.push(format!(
1175                    "{} = ENV.fetch('{env_key}', nil) || \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1176                    arg.name,
1177                ));
1178            } else {
1179                setup_lines.push(format!(
1180                    "{} = \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1181                    arg.name,
1182                ));
1183            }
1184            parts.push(arg.name.clone());
1185            continue;
1186        }
1187
1188        // Handle bytes arguments: load from file if needed
1189        if arg.arg_type == "bytes" {
1190            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1191            for _ in 0..skipped_optional_count {
1192                parts.push("nil".to_string());
1193            }
1194            skipped_optional_count = 0;
1195            let resolved = resolve_field(input, &arg.field);
1196            if let Some(s) = resolved.as_str() {
1197                if is_file_path(s) {
1198                    // File path: load with File.read and convert to bytes array
1199                    setup_lines.push(format!("{} = File.read(\"{}\").bytes", arg.name, s));
1200                } else if is_base64(s) {
1201                    // Base64: decode it
1202                    setup_lines.push(format!("{} = Base64.decode64(\"{}\").bytes", arg.name, s));
1203                } else {
1204                    // Inline text: encode to binary and convert to bytes array
1205                    let escaped = ruby_string_literal(s);
1206                    setup_lines.push(format!("{} = {}.b.bytes", arg.name, escaped));
1207                }
1208                parts.push(arg.name.clone());
1209            } else {
1210                parts.push("nil".to_string());
1211            }
1212            continue;
1213        }
1214
1215        // Handle file_path arguments: pass the path string as-is
1216        if arg.arg_type == "file_path" {
1217            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1218            for _ in 0..skipped_optional_count {
1219                parts.push("nil".to_string());
1220            }
1221            skipped_optional_count = 0;
1222            let resolved = resolve_field(input, &arg.field);
1223            if let Some(s) = resolved.as_str() {
1224                let escaped = ruby_string_literal(s);
1225                parts.push(escaped);
1226            } else if arg.optional {
1227                skipped_optional_count += 1;
1228                continue;
1229            } else {
1230                parts.push("''".to_string());
1231            }
1232            continue;
1233        }
1234
1235        if arg.arg_type == "handle" {
1236            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1237            for _ in 0..skipped_optional_count {
1238                parts.push("nil".to_string());
1239            }
1240            skipped_optional_count = 0;
1241            // Generate a create_engine (or equivalent) call and pass the variable.
1242            let constructor_name = format!("create_{}", arg.name.to_snake_case());
1243            let config_value = resolve_field(input, &arg.field);
1244            if config_value.is_null()
1245                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1246            {
1247                setup_lines.push(format!("{} = {call_receiver}.{constructor_name}(nil)", arg.name,));
1248            } else {
1249                let literal = json_to_ruby(config_value);
1250                let name = &arg.name;
1251                setup_lines.push(format!("{name}_config = {literal}"));
1252                setup_lines.push(format!(
1253                    "{} = {call_receiver}.{constructor_name}({name}_config.to_json)",
1254                    arg.name,
1255                    name = name,
1256                ));
1257            }
1258            parts.push(arg.name.clone());
1259            continue;
1260        }
1261
1262        let resolved = resolve_field(input, &arg.field);
1263        let val = if resolved.is_null() { None } else { Some(resolved) };
1264        match val {
1265            None | Some(serde_json::Value::Null) if arg.optional => {
1266                // Optional arg with no fixture value: defer; emit nil only if a later arg is present.
1267                skipped_optional_count += 1;
1268                continue;
1269            }
1270            None | Some(serde_json::Value::Null) => {
1271                // Required arg with no fixture value: flush deferred nils, then pass a default.
1272                for _ in 0..skipped_optional_count {
1273                    parts.push("nil".to_string());
1274                }
1275                skipped_optional_count = 0;
1276                let default_val = match arg.arg_type.as_str() {
1277                    "string" => "''".to_string(),
1278                    "int" | "integer" => "0".to_string(),
1279                    "float" | "number" => "0.0".to_string(),
1280                    "bool" | "boolean" => "false".to_string(),
1281                    _ => "nil".to_string(),
1282                };
1283                parts.push(default_val);
1284            }
1285            Some(v) => {
1286                // Flush deferred nil placeholders for skipped optional args that precede this one.
1287                for _ in 0..skipped_optional_count {
1288                    parts.push("nil".to_string());
1289                }
1290                skipped_optional_count = 0;
1291                // For json_object args with options_type, construct a typed options object.
1292                // When result_is_simple, the binding accepts a plain Hash (no wrapper class).
1293                if arg.arg_type == "json_object" && !v.is_null() {
1294                    // Check for batch item arrays (element_type set to BatchBytesItem/BatchFileItem)
1295                    if let Some(elem_type) = &arg.element_type {
1296                        if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && v.is_array() {
1297                            parts.push(emit_ruby_batch_item_array(v, elem_type));
1298                            continue;
1299                        }
1300                    }
1301                    // Otherwise handle regular options_type objects
1302                    if let (Some(opts_type), Some(obj)) = (options_type, v.as_object()) {
1303                        let kwargs: Vec<String> = obj
1304                            .iter()
1305                            .map(|(k, vv)| {
1306                                let snake_key = k.to_snake_case();
1307                                let rb_val = if enum_fields.contains_key(k) {
1308                                    if let Some(s) = vv.as_str() {
1309                                        let snake_val = s.to_snake_case();
1310                                        format!("'{snake_val}'")
1311                                    } else {
1312                                        json_to_ruby(vv)
1313                                    }
1314                                } else {
1315                                    json_to_ruby(vv)
1316                                };
1317                                format!("{snake_key}: {rb_val}")
1318                            })
1319                            .collect();
1320                        if result_is_simple {
1321                            parts.push(format!("{{{}}}", kwargs.join(", ")));
1322                        } else {
1323                            parts.push(format!("{opts_type}.new({})", kwargs.join(", ")));
1324                        }
1325                        continue;
1326                    }
1327                }
1328                parts.push(json_to_ruby(v));
1329            }
1330        }
1331    }
1332
1333    (setup_lines, parts.join(", "))
1334}
1335
1336fn render_assertion(
1337    out: &mut String,
1338    assertion: &Assertion,
1339    result_var: &str,
1340    field_resolver: &FieldResolver,
1341    result_is_simple: bool,
1342    e2e_config: &E2eConfig,
1343    per_call_enum_fields: &HashMap<String, String>,
1344) {
1345    // For simple-result methods (e.g. `speech` returning bytes), every field-based
1346    // assertion targets the result itself — there's no struct to access. Drop
1347    // length-only assertions onto the result directly and skip anything else.
1348    if result_is_simple {
1349        if let Some(f) = &assertion.field {
1350            if !f.is_empty() {
1351                match assertion.assertion_type.as_str() {
1352                    "not_empty" => {
1353                        out.push_str(&format!("    expect({result_var}.to_s).not_to be_empty\n"));
1354                        return;
1355                    }
1356                    "is_empty" => {
1357                        out.push_str(&format!("    expect({result_var}.to_s).to be_empty\n"));
1358                        return;
1359                    }
1360                    "count_equals" => {
1361                        if let Some(val) = &assertion.value {
1362                            let rb_val = json_to_ruby(val);
1363                            out.push_str(&format!("    expect({result_var}.length).to eq({rb_val})\n"));
1364                        }
1365                        return;
1366                    }
1367                    "count_min" => {
1368                        if let Some(val) = &assertion.value {
1369                            let rb_val = json_to_ruby(val);
1370                            out.push_str(&format!("    expect({result_var}.length).to be >= {rb_val}\n"));
1371                        }
1372                        return;
1373                    }
1374                    _ => {
1375                        out.push_str(&format!(
1376                            "    # skipped: field '{f}' not applicable for simple result type\n"
1377                        ));
1378                        return;
1379                    }
1380                }
1381            }
1382        }
1383    }
1384    // Handle synthetic / derived fields before the is_valid_for_result check
1385    // so they are never treated as struct attribute accesses on the result.
1386    if let Some(f) = &assertion.field {
1387        match f.as_str() {
1388            "chunks_have_content" => {
1389                let pred = format!("({result_var}.chunks || []).all? {{ |c| c.content && !c.content.empty? }}");
1390                match assertion.assertion_type.as_str() {
1391                    "is_true" => {
1392                        out.push_str(&format!("    expect({pred}).to be(true)\n"));
1393                    }
1394                    "is_false" => {
1395                        out.push_str(&format!("    expect({pred}).to be(false)\n"));
1396                    }
1397                    _ => {
1398                        out.push_str(&format!(
1399                            "    # skipped: unsupported assertion type on synthetic field '{f}'\n"
1400                        ));
1401                    }
1402                }
1403                return;
1404            }
1405            "chunks_have_embeddings" => {
1406                let pred =
1407                    format!("({result_var}.chunks || []).all? {{ |c| !c.embedding.nil? && !c.embedding.empty? }}");
1408                match assertion.assertion_type.as_str() {
1409                    "is_true" => {
1410                        out.push_str(&format!("    expect({pred}).to be(true)\n"));
1411                    }
1412                    "is_false" => {
1413                        out.push_str(&format!("    expect({pred}).to be(false)\n"));
1414                    }
1415                    _ => {
1416                        out.push_str(&format!(
1417                            "    # skipped: unsupported assertion type on synthetic field '{f}'\n"
1418                        ));
1419                    }
1420                }
1421                return;
1422            }
1423            // ---- EmbedResponse virtual fields ----
1424            // embed_texts returns Array<Array<Float>> in Ruby — no wrapper struct.
1425            // result_var is the embedding matrix; use it directly.
1426            "embeddings" => {
1427                match assertion.assertion_type.as_str() {
1428                    "count_equals" => {
1429                        if let Some(val) = &assertion.value {
1430                            let rb_val = json_to_ruby(val);
1431                            out.push_str(&format!("    expect({result_var}.length).to eq({rb_val})\n"));
1432                        }
1433                    }
1434                    "count_min" => {
1435                        if let Some(val) = &assertion.value {
1436                            let rb_val = json_to_ruby(val);
1437                            out.push_str(&format!("    expect({result_var}.length).to be >= {rb_val}\n"));
1438                        }
1439                    }
1440                    "not_empty" => {
1441                        out.push_str(&format!("    expect({result_var}).not_to be_empty\n"));
1442                    }
1443                    "is_empty" => {
1444                        out.push_str(&format!("    expect({result_var}).to be_empty\n"));
1445                    }
1446                    _ => {
1447                        out.push_str("    # skipped: unsupported assertion type on synthetic field 'embeddings'\n");
1448                    }
1449                }
1450                return;
1451            }
1452            "embedding_dimensions" => {
1453                let expr = format!("({result_var}.empty? ? 0 : {result_var}[0].length)");
1454                match assertion.assertion_type.as_str() {
1455                    "equals" => {
1456                        if let Some(val) = &assertion.value {
1457                            let rb_val = json_to_ruby(val);
1458                            out.push_str(&format!("    expect({expr}).to eq({rb_val})\n"));
1459                        }
1460                    }
1461                    "greater_than" => {
1462                        if let Some(val) = &assertion.value {
1463                            let rb_val = json_to_ruby(val);
1464                            out.push_str(&format!("    expect({expr}).to be > {rb_val}\n"));
1465                        }
1466                    }
1467                    _ => {
1468                        out.push_str(
1469                            "    # skipped: unsupported assertion type on synthetic field 'embedding_dimensions'\n",
1470                        );
1471                    }
1472                }
1473                return;
1474            }
1475            "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1476                let pred = match f.as_str() {
1477                    "embeddings_valid" => {
1478                        format!("{result_var}.all? {{ |e| !e.empty? }}")
1479                    }
1480                    "embeddings_finite" => {
1481                        format!("{result_var}.all? {{ |e| e.all? {{ |v| v.finite? }} }}")
1482                    }
1483                    "embeddings_non_zero" => {
1484                        format!("{result_var}.all? {{ |e| e.any? {{ |v| v != 0.0 }} }}")
1485                    }
1486                    "embeddings_normalized" => {
1487                        format!("{result_var}.all? {{ |e| n = e.sum {{ |v| v * v }}; (n - 1.0).abs < 1e-3 }}")
1488                    }
1489                    _ => unreachable!(),
1490                };
1491                match assertion.assertion_type.as_str() {
1492                    "is_true" => {
1493                        out.push_str(&format!("    expect({pred}).to be(true)\n"));
1494                    }
1495                    "is_false" => {
1496                        out.push_str(&format!("    expect({pred}).to be(false)\n"));
1497                    }
1498                    _ => {
1499                        out.push_str(&format!(
1500                            "    # skipped: unsupported assertion type on synthetic field '{f}'\n"
1501                        ));
1502                    }
1503                }
1504                return;
1505            }
1506            // ---- keywords / keywords_count ----
1507            // Ruby ExtractionResult does not expose extracted_keywords; skip.
1508            "keywords" | "keywords_count" => {
1509                out.push_str(&format!(
1510                    "    # skipped: field '{f}' not available on Ruby ExtractionResult\n"
1511                ));
1512                return;
1513            }
1514            _ => {}
1515        }
1516    }
1517
1518    // Skip assertions on fields that don't exist on the result type.
1519    if let Some(f) = &assertion.field {
1520        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1521            out.push_str(&format!("    # skipped: field '{f}' not available on result type\n"));
1522            return;
1523        }
1524    }
1525
1526    // When result_is_simple, skip assertions that reference non-content fields.
1527    if result_is_simple {
1528        if let Some(f) = &assertion.field {
1529            let f_lower = f.to_lowercase();
1530            if !f.is_empty()
1531                && f_lower != "content"
1532                && (f_lower.starts_with("metadata")
1533                    || f_lower.starts_with("document")
1534                    || f_lower.starts_with("structure"))
1535            {
1536                return;
1537            }
1538        }
1539    }
1540
1541    // result_is_simple: treat the result itself as the content string, but only
1542    // when there is no explicit field (or the field is "content"). Count/length
1543    // assertions on named fields (e.g. "warnings") must still walk the field path.
1544    let field_expr = match &assertion.field {
1545        Some(f) if !f.is_empty() && (!result_is_simple || !f.eq_ignore_ascii_case("content")) => {
1546            field_resolver.accessor(f, "ruby", result_var)
1547        }
1548        _ => result_var.to_string(),
1549    };
1550
1551    // For string equality, strip trailing whitespace to handle trailing newlines
1552    // from the converter. Ruby enum fields (Magnus binds Rust enums as Symbols),
1553    // are coerced to String via .to_s so `eq("stop")` matches `:stop`. Look up the
1554    // field in both the global `[crates.e2e] fields_enum` set AND the per-call
1555    // override `[crates.e2e.calls.<x>.overrides.<lang>] enum_fields = { ... }` —
1556    // downstream config that already labels e.g. `status = "BatchStatus"` for the
1557    // Java/C#/Python sides should apply here too without a Ruby-only duplicate.
1558    let field_is_enum = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
1559        let resolved = field_resolver.resolve(f);
1560        e2e_config.fields_enum.contains(f)
1561            || e2e_config.fields_enum.contains(resolved)
1562            || per_call_enum_fields.contains_key(f)
1563            || per_call_enum_fields.contains_key(resolved)
1564    });
1565    let stripped_field_expr = if result_is_simple {
1566        format!("{field_expr}.to_s.strip")
1567    } else if field_is_enum {
1568        format!("{field_expr}.to_s")
1569    } else {
1570        field_expr.clone()
1571    };
1572
1573    // Detect whether the assertion field resolves to an array type so that
1574    // contains assertions can iterate items instead of calling .to_s on the array.
1575    let field_is_array = assertion
1576        .field
1577        .as_deref()
1578        .filter(|f| !f.is_empty())
1579        .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1580
1581    match assertion.assertion_type.as_str() {
1582        "equals" => {
1583            if let Some(expected) = &assertion.value {
1584                let is_boolean_val = expected.as_bool().is_some();
1585                let bool_val = expected
1586                    .as_bool()
1587                    .map(|b| if b { "true" } else { "false" })
1588                    .unwrap_or("");
1589                let rb_val = json_to_ruby(expected);
1590
1591                let rendered = crate::template_env::render(
1592                    "ruby/assertion.jinja",
1593                    minijinja::context! {
1594                        assertion_type => "equals",
1595                        stripped_field_expr => stripped_field_expr.clone(),
1596                        is_boolean_val => is_boolean_val,
1597                        bool_val => bool_val,
1598                        expected_val => rb_val,
1599                    },
1600                );
1601                out.push_str(&rendered);
1602            }
1603        }
1604        "contains" => {
1605            if let Some(expected) = &assertion.value {
1606                let rb_val = json_to_ruby(expected);
1607                let rendered = crate::template_env::render(
1608                    "ruby/assertion.jinja",
1609                    minijinja::context! {
1610                        assertion_type => "contains",
1611                        field_expr => field_expr.clone(),
1612                        field_is_array => field_is_array && expected.is_string(),
1613                        expected_val => rb_val,
1614                    },
1615                );
1616                out.push_str(&rendered);
1617            }
1618        }
1619        "contains_all" => {
1620            if let Some(values) = &assertion.values {
1621                let values_list: Vec<String> = values.iter().map(json_to_ruby).collect();
1622                let rendered = crate::template_env::render(
1623                    "ruby/assertion.jinja",
1624                    minijinja::context! {
1625                        assertion_type => "contains_all",
1626                        field_expr => field_expr.clone(),
1627                        field_is_array => field_is_array,
1628                        values_list => values_list,
1629                    },
1630                );
1631                out.push_str(&rendered);
1632            }
1633        }
1634        "not_contains" => {
1635            if let Some(expected) = &assertion.value {
1636                let rb_val = json_to_ruby(expected);
1637                let rendered = crate::template_env::render(
1638                    "ruby/assertion.jinja",
1639                    minijinja::context! {
1640                        assertion_type => "not_contains",
1641                        field_expr => field_expr.clone(),
1642                        field_is_array => field_is_array && expected.is_string(),
1643                        expected_val => rb_val,
1644                    },
1645                );
1646                out.push_str(&rendered);
1647            }
1648        }
1649        "not_empty" => {
1650            let rendered = crate::template_env::render(
1651                "ruby/assertion.jinja",
1652                minijinja::context! {
1653                    assertion_type => "not_empty",
1654                    field_expr => field_expr.clone(),
1655                },
1656            );
1657            out.push_str(&rendered);
1658        }
1659        "is_empty" => {
1660            let rendered = crate::template_env::render(
1661                "ruby/assertion.jinja",
1662                minijinja::context! {
1663                    assertion_type => "is_empty",
1664                    field_expr => field_expr.clone(),
1665                },
1666            );
1667            out.push_str(&rendered);
1668        }
1669        "contains_any" => {
1670            if let Some(values) = &assertion.values {
1671                let items: Vec<String> = values.iter().map(json_to_ruby).collect();
1672                let rendered = crate::template_env::render(
1673                    "ruby/assertion.jinja",
1674                    minijinja::context! {
1675                        assertion_type => "contains_any",
1676                        field_expr => field_expr.clone(),
1677                        values_list => items,
1678                    },
1679                );
1680                out.push_str(&rendered);
1681            }
1682        }
1683        "greater_than" => {
1684            if let Some(val) = &assertion.value {
1685                let rb_val = json_to_ruby(val);
1686                let rendered = crate::template_env::render(
1687                    "ruby/assertion.jinja",
1688                    minijinja::context! {
1689                        assertion_type => "greater_than",
1690                        field_expr => field_expr.clone(),
1691                        expected_val => rb_val,
1692                    },
1693                );
1694                out.push_str(&rendered);
1695            }
1696        }
1697        "less_than" => {
1698            if let Some(val) = &assertion.value {
1699                let rb_val = json_to_ruby(val);
1700                let rendered = crate::template_env::render(
1701                    "ruby/assertion.jinja",
1702                    minijinja::context! {
1703                        assertion_type => "less_than",
1704                        field_expr => field_expr.clone(),
1705                        expected_val => rb_val,
1706                    },
1707                );
1708                out.push_str(&rendered);
1709            }
1710        }
1711        "greater_than_or_equal" => {
1712            if let Some(val) = &assertion.value {
1713                let rb_val = json_to_ruby(val);
1714                let rendered = crate::template_env::render(
1715                    "ruby/assertion.jinja",
1716                    minijinja::context! {
1717                        assertion_type => "greater_than_or_equal",
1718                        field_expr => field_expr.clone(),
1719                        expected_val => rb_val,
1720                    },
1721                );
1722                out.push_str(&rendered);
1723            }
1724        }
1725        "less_than_or_equal" => {
1726            if let Some(val) = &assertion.value {
1727                let rb_val = json_to_ruby(val);
1728                let rendered = crate::template_env::render(
1729                    "ruby/assertion.jinja",
1730                    minijinja::context! {
1731                        assertion_type => "less_than_or_equal",
1732                        field_expr => field_expr.clone(),
1733                        expected_val => rb_val,
1734                    },
1735                );
1736                out.push_str(&rendered);
1737            }
1738        }
1739        "starts_with" => {
1740            if let Some(expected) = &assertion.value {
1741                let rb_val = json_to_ruby(expected);
1742                let rendered = crate::template_env::render(
1743                    "ruby/assertion.jinja",
1744                    minijinja::context! {
1745                        assertion_type => "starts_with",
1746                        field_expr => field_expr.clone(),
1747                        expected_val => rb_val,
1748                    },
1749                );
1750                out.push_str(&rendered);
1751            }
1752        }
1753        "ends_with" => {
1754            if let Some(expected) = &assertion.value {
1755                let rb_val = json_to_ruby(expected);
1756                let rendered = crate::template_env::render(
1757                    "ruby/assertion.jinja",
1758                    minijinja::context! {
1759                        assertion_type => "ends_with",
1760                        field_expr => field_expr.clone(),
1761                        expected_val => rb_val,
1762                    },
1763                );
1764                out.push_str(&rendered);
1765            }
1766        }
1767        "min_length" | "max_length" | "count_min" | "count_equals" => {
1768            if let Some(val) = &assertion.value {
1769                if let Some(n) = val.as_u64() {
1770                    let rendered = crate::template_env::render(
1771                        "ruby/assertion.jinja",
1772                        minijinja::context! {
1773                            assertion_type => assertion.assertion_type.as_str(),
1774                            field_expr => field_expr.clone(),
1775                            check_n => n,
1776                        },
1777                    );
1778                    out.push_str(&rendered);
1779                }
1780            }
1781        }
1782        "is_true" => {
1783            let rendered = crate::template_env::render(
1784                "ruby/assertion.jinja",
1785                minijinja::context! {
1786                    assertion_type => "is_true",
1787                    field_expr => field_expr.clone(),
1788                },
1789            );
1790            out.push_str(&rendered);
1791        }
1792        "is_false" => {
1793            let rendered = crate::template_env::render(
1794                "ruby/assertion.jinja",
1795                minijinja::context! {
1796                    assertion_type => "is_false",
1797                    field_expr => field_expr.clone(),
1798                },
1799            );
1800            out.push_str(&rendered);
1801        }
1802        "method_result" => {
1803            if let Some(method_name) = &assertion.method {
1804                // Derive call_receiver for module-level helper calls.
1805                let lang = "ruby";
1806                let call = &e2e_config.call;
1807                let overrides = call.overrides.get(lang);
1808                let module_path = overrides
1809                    .and_then(|o| o.module.as_ref())
1810                    .cloned()
1811                    .unwrap_or_else(|| call.module.clone());
1812                let call_receiver = ruby_module_name(&module_path);
1813
1814                let call_expr =
1815                    build_ruby_method_call(&call_receiver, result_var, method_name, assertion.args.as_ref());
1816                let check = assertion.check.as_deref().unwrap_or("is_true");
1817
1818                let (check_val_str, is_boolean_check, bool_check_val, check_n_val) = match check {
1819                    "equals" => {
1820                        if let Some(val) = &assertion.value {
1821                            let is_bool = val.as_bool().is_some();
1822                            let bool_str = val.as_bool().map(|b| if b { "true" } else { "false" }).unwrap_or("");
1823                            let rb_val = json_to_ruby(val);
1824                            (rb_val, is_bool, bool_str.to_string(), 0)
1825                        } else {
1826                            (String::new(), false, String::new(), 0)
1827                        }
1828                    }
1829                    "greater_than_or_equal" => {
1830                        if let Some(val) = &assertion.value {
1831                            (json_to_ruby(val), false, String::new(), 0)
1832                        } else {
1833                            (String::new(), false, String::new(), 0)
1834                        }
1835                    }
1836                    "count_min" => {
1837                        if let Some(val) = &assertion.value {
1838                            let n = val.as_u64().unwrap_or(0);
1839                            (String::new(), false, String::new(), n)
1840                        } else {
1841                            (String::new(), false, String::new(), 0)
1842                        }
1843                    }
1844                    "contains" => {
1845                        if let Some(val) = &assertion.value {
1846                            (json_to_ruby(val), false, String::new(), 0)
1847                        } else {
1848                            (String::new(), false, String::new(), 0)
1849                        }
1850                    }
1851                    _ => (String::new(), false, String::new(), 0),
1852                };
1853
1854                let rendered = crate::template_env::render(
1855                    "ruby/assertion.jinja",
1856                    minijinja::context! {
1857                        assertion_type => "method_result",
1858                        call_expr => call_expr,
1859                        check => check,
1860                        check_val => check_val_str,
1861                        is_boolean_check => is_boolean_check,
1862                        bool_check_val => bool_check_val,
1863                        check_n => check_n_val,
1864                    },
1865                );
1866                out.push_str(&rendered);
1867            } else {
1868                panic!("Ruby e2e generator: method_result assertion missing 'method' field");
1869            }
1870        }
1871        "matches_regex" => {
1872            if let Some(expected) = &assertion.value {
1873                let rb_val = json_to_ruby(expected);
1874                let rendered = crate::template_env::render(
1875                    "ruby/assertion.jinja",
1876                    minijinja::context! {
1877                        assertion_type => "matches_regex",
1878                        field_expr => field_expr.clone(),
1879                        expected_val => rb_val,
1880                    },
1881                );
1882                out.push_str(&rendered);
1883            }
1884        }
1885        "not_error" => {
1886            // Already handled by the call succeeding without exception.
1887        }
1888        "error" => {
1889            // Handled at the example level.
1890        }
1891        other => {
1892            panic!("Ruby e2e generator: unsupported assertion type: {other}");
1893        }
1894    }
1895}
1896
1897/// Build a Ruby call expression for a `method_result` assertion on a tree-sitter Tree.
1898/// Maps method names to the appropriate Ruby method or module-function calls.
1899fn build_ruby_method_call(
1900    call_receiver: &str,
1901    result_var: &str,
1902    method_name: &str,
1903    args: Option<&serde_json::Value>,
1904) -> String {
1905    match method_name {
1906        "root_child_count" => format!("{result_var}.root_node.child_count"),
1907        "root_node_type" => format!("{result_var}.root_node.type"),
1908        "named_children_count" => format!("{result_var}.root_node.named_child_count"),
1909        "has_error_nodes" => format!("{call_receiver}.tree_has_error_nodes({result_var})"),
1910        "error_count" | "tree_error_count" => format!("{call_receiver}.tree_error_count({result_var})"),
1911        "tree_to_sexp" => format!("{call_receiver}.tree_to_sexp({result_var})"),
1912        "contains_node_type" => {
1913            let node_type = args
1914                .and_then(|a| a.get("node_type"))
1915                .and_then(|v| v.as_str())
1916                .unwrap_or("");
1917            format!("{call_receiver}.tree_contains_node_type({result_var}, \"{node_type}\")")
1918        }
1919        "find_nodes_by_type" => {
1920            let node_type = args
1921                .and_then(|a| a.get("node_type"))
1922                .and_then(|v| v.as_str())
1923                .unwrap_or("");
1924            format!("{call_receiver}.find_nodes_by_type({result_var}, \"{node_type}\")")
1925        }
1926        "run_query" => {
1927            let query_source = args
1928                .and_then(|a| a.get("query_source"))
1929                .and_then(|v| v.as_str())
1930                .unwrap_or("");
1931            let language = args
1932                .and_then(|a| a.get("language"))
1933                .and_then(|v| v.as_str())
1934                .unwrap_or("");
1935            format!("{call_receiver}.run_query({result_var}, \"{language}\", \"{query_source}\", source)")
1936        }
1937        _ => format!("{result_var}.{method_name}"),
1938    }
1939}
1940
1941/// Convert a module path (e.g., "html_to_markdown") to Ruby PascalCase module name
1942/// (e.g., "HtmlToMarkdown").
1943fn ruby_module_name(module_path: &str) -> String {
1944    use heck::ToUpperCamelCase;
1945    module_path.to_upper_camel_case()
1946}
1947
1948/// Convert a `serde_json::Value` to a Ruby literal string, preferring single quotes.
1949fn json_to_ruby(value: &serde_json::Value) -> String {
1950    match value {
1951        serde_json::Value::String(s) => ruby_string_literal(s),
1952        serde_json::Value::Bool(true) => "true".to_string(),
1953        serde_json::Value::Bool(false) => "false".to_string(),
1954        serde_json::Value::Number(n) => n.to_string(),
1955        serde_json::Value::Null => "nil".to_string(),
1956        serde_json::Value::Array(arr) => {
1957            let items: Vec<String> = arr.iter().map(json_to_ruby).collect();
1958            format!("[{}]", items.join(", "))
1959        }
1960        serde_json::Value::Object(map) => {
1961            let items: Vec<String> = map
1962                .iter()
1963                .map(|(k, v)| format!("{} => {}", ruby_string_literal(k), json_to_ruby(v)))
1964                .collect();
1965            format!("{{ {} }}", items.join(", "))
1966        }
1967    }
1968}
1969
1970// ---------------------------------------------------------------------------
1971// Visitor generation
1972// ---------------------------------------------------------------------------
1973
1974/// Build a Ruby visitor object and add setup lines. Returns the visitor expression.
1975fn build_ruby_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) -> String {
1976    setup_lines.push("visitor = Class.new do".to_string());
1977    for (method_name, action) in &visitor_spec.callbacks {
1978        emit_ruby_visitor_method(setup_lines, method_name, action);
1979    }
1980    setup_lines.push("end.new".to_string());
1981    "visitor".to_string()
1982}
1983
1984/// Emit a Ruby visitor method for a callback action.
1985fn emit_ruby_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
1986    let params = match method_name {
1987        "visit_link" => "ctx, href, text, title",
1988        "visit_image" => "ctx, src, alt, title",
1989        "visit_heading" => "ctx, level, text, id",
1990        "visit_code_block" => "ctx, lang, code",
1991        "visit_code_inline"
1992        | "visit_strong"
1993        | "visit_emphasis"
1994        | "visit_strikethrough"
1995        | "visit_underline"
1996        | "visit_subscript"
1997        | "visit_superscript"
1998        | "visit_mark"
1999        | "visit_button"
2000        | "visit_summary"
2001        | "visit_figcaption"
2002        | "visit_definition_term"
2003        | "visit_definition_description" => "ctx, text",
2004        "visit_text" => "ctx, text",
2005        "visit_list_item" => "ctx, ordered, marker, text",
2006        "visit_blockquote" => "ctx, content, depth",
2007        "visit_table_row" => "ctx, cells, is_header",
2008        "visit_custom_element" => "ctx, tag_name, html",
2009        "visit_form" => "ctx, action_url, method",
2010        "visit_input" => "ctx, input_type, name, value",
2011        "visit_audio" | "visit_video" | "visit_iframe" => "ctx, src",
2012        "visit_details" => "ctx, is_open",
2013        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "ctx, output",
2014        "visit_list_start" => "ctx, ordered",
2015        "visit_list_end" => "ctx, ordered, output",
2016        _ => "ctx",
2017    };
2018
2019    // Pre-compute action type and values
2020    let (action_type, action_value) = match action {
2021        CallbackAction::Skip => ("skip", String::new()),
2022        CallbackAction::Continue => ("continue", String::new()),
2023        CallbackAction::PreserveHtml => ("preserve_html", String::new()),
2024        CallbackAction::Custom { output } => {
2025            let escaped = ruby_string_literal(output);
2026            ("custom", escaped)
2027        }
2028        CallbackAction::CustomTemplate { template } => {
2029            let interpolated = ruby_template_to_interpolation(template);
2030            ("custom", format!("\"{interpolated}\""))
2031        }
2032    };
2033
2034    let rendered = crate::template_env::render(
2035        "ruby/visitor_method.jinja",
2036        minijinja::context! {
2037            method_name => method_name,
2038            params => params,
2039            action_type => action_type,
2040            action_value => action_value,
2041        },
2042    );
2043    for line in rendered.lines() {
2044        setup_lines.push(line.to_string());
2045    }
2046}
2047
2048/// Classify a fixture string value that maps to a `bytes` argument.
2049///
2050/// Returns true if the value looks like a file path (e.g. "pdf/fake_memo.pdf").
2051/// File paths have the pattern: alphanumeric/something.extension
2052fn is_file_path(s: &str) -> bool {
2053    if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2054        return false;
2055    }
2056
2057    let first = s.chars().next().unwrap_or('\0');
2058    if first.is_ascii_alphanumeric() || first == '_' {
2059        if let Some(slash_pos) = s.find('/') {
2060            if slash_pos > 0 {
2061                let after_slash = &s[slash_pos + 1..];
2062                if after_slash.contains('.') && !after_slash.is_empty() {
2063                    return true;
2064                }
2065            }
2066        }
2067    }
2068
2069    false
2070}
2071
2072/// Check if a string looks like base64-encoded data.
2073/// If it's not a file path or inline text, assume it's base64.
2074fn is_base64(s: &str) -> bool {
2075    if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2076        return false;
2077    }
2078
2079    if is_file_path(s) {
2080        return false;
2081    }
2082
2083    true
2084}