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