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