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    crate::template_env::render(
1132        "ruby/test_function.jinja",
1133        minijinja::context! {
1134            test_name => test_name,
1135            description => description,
1136            expects_error => expects_error,
1137            setup_lines => setup_lines,
1138            call_expr => call_expr,
1139            result_var => result_var,
1140            assertions_rendered => assertions_rendered,
1141            has_usable => has_usable,
1142            returns_void => returns_void,
1143            client_factory => client_factory,
1144            fixture_id => fixture_id,
1145            call_receiver => call_receiver,
1146            has_mock => has_mock,
1147            api_key_var => api_key_var,
1148            has_mock_and_key => has_mock_and_key,
1149            is_only_not_error => is_only_not_error,
1150        },
1151    )
1152}
1153
1154/// Build setup lines (e.g. handle creation) and the argument list for the function call.
1155///
1156/// Returns `(setup_lines, args_string)`.
1157/// Emit Ruby batch item constructors for BatchBytesItem or BatchFileItem arrays.
1158fn emit_ruby_batch_item_array(arr: &serde_json::Value, elem_type: &str, module_name: &str) -> String {
1159    if let Some(items) = arr.as_array() {
1160        let item_strs: Vec<String> = items
1161            .iter()
1162            .filter_map(|item| {
1163                if let Some(obj) = item.as_object() {
1164                    match elem_type {
1165                        "BatchBytesItem" => {
1166                            let content = obj.get("content").and_then(|v| v.as_array());
1167                            let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1168                            let config = obj.get("config");
1169                            let content_code = if let Some(arr) = content {
1170                                let bytes: Vec<String> =
1171                                    arr.iter().filter_map(|v| v.as_u64().map(|n| n.to_string())).collect();
1172                                // Pass as Ruby array - Magnus will convert Array<u8> to Vec<u8>
1173                                format!("[{}]", bytes.join(", "))
1174                            } else {
1175                                "[]".to_string()
1176                            };
1177                            let config_arg = if let Some(cfg) = config {
1178                                if cfg.is_null() {
1179                                    "nil".to_string()
1180                                } else {
1181                                    json_to_ruby(cfg)
1182                                }
1183                            } else {
1184                                "nil".to_string()
1185                            };
1186                            Some(format!(
1187                                "{}::{}.new(content: {}, mime_type: \"{}\", config: {})",
1188                                module_name, elem_type, content_code, mime_type, config_arg
1189                            ))
1190                        }
1191                        "BatchFileItem" => {
1192                            let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1193                            let config = obj.get("config");
1194                            let config_arg = if let Some(cfg) = config {
1195                                if cfg.is_null() {
1196                                    "nil".to_string()
1197                                } else {
1198                                    json_to_ruby(cfg)
1199                                }
1200                            } else {
1201                                "nil".to_string()
1202                            };
1203                            Some(format!(
1204                                "{}::{}.new(path: \"{}\", config: {})",
1205                                module_name, elem_type, path, config_arg
1206                            ))
1207                        }
1208                        _ => None,
1209                    }
1210                } else {
1211                    None
1212                }
1213            })
1214            .collect();
1215        format!("[{}]", item_strs.join(", "))
1216    } else {
1217        "[]".to_string()
1218    }
1219}
1220
1221#[allow(clippy::too_many_arguments)]
1222fn build_args_and_setup(
1223    input: &serde_json::Value,
1224    args: &[crate::config::ArgMapping],
1225    call_receiver: &str,
1226    module_name: &str,
1227    options_type: Option<&str>,
1228    enum_fields: &HashMap<String, String>,
1229    result_is_simple: bool,
1230    fixture: &crate::fixture::Fixture,
1231    adapter_request_type: Option<&str>,
1232) -> (Vec<String>, String) {
1233    let fixture_id = &fixture.id;
1234    if args.is_empty() {
1235        // No args config: pass the whole input only when it's non-empty.
1236        // Functions with no parameters have empty input and must be called
1237        // with no arguments — not with `{}` or `nil`.
1238        let is_empty_input = match input {
1239            serde_json::Value::Null => true,
1240            serde_json::Value::Object(m) => m.is_empty(),
1241            _ => false,
1242        };
1243        if is_empty_input {
1244            return (Vec::new(), String::new());
1245        }
1246        return (Vec::new(), json_to_ruby(input));
1247    }
1248
1249    let mut setup_lines: Vec<String> = Vec::new();
1250    let mut parts: Vec<String> = Vec::new();
1251    // Track optional args that were skipped; if a later arg is emitted we must back-fill nil
1252    // to preserve positional correctness (e.g. extract_file(path, nil, config)).
1253    let mut skipped_optional_count: usize = 0;
1254
1255    for arg in args {
1256        if arg.arg_type == "mock_url" {
1257            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1258            for _ in 0..skipped_optional_count {
1259                parts.push("nil".to_string());
1260            }
1261            skipped_optional_count = 0;
1262            if fixture.has_host_root_route() {
1263                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1264                setup_lines.push(format!(
1265                    "{} = ENV.fetch('{env_key}', nil) || \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1266                    arg.name,
1267                ));
1268            } else {
1269                setup_lines.push(format!(
1270                    "{} = \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
1271                    arg.name,
1272                ));
1273            }
1274            if let Some(req_type) = adapter_request_type {
1275                let req_var = format!("{}_req", arg.name);
1276                // Derive the module qualifier from module_name (e.g. "Kreuzcrawl")
1277                let mod_qualifier = ruby_module_name(module_name);
1278                setup_lines.push(format!(
1279                    "{req_var} = {mod_qualifier}::{req_type}.new(url: {})",
1280                    arg.name
1281                ));
1282                parts.push(req_var);
1283            } else {
1284                parts.push(arg.name.clone());
1285            }
1286            continue;
1287        }
1288
1289        // Handle bytes arguments: load from file if needed
1290        if arg.arg_type == "bytes" {
1291            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1292            for _ in 0..skipped_optional_count {
1293                parts.push("nil".to_string());
1294            }
1295            skipped_optional_count = 0;
1296            let resolved = resolve_field(input, &arg.field);
1297            if let Some(s) = resolved.as_str() {
1298                if is_file_path(s) {
1299                    // File path: load with File.read and convert to bytes array
1300                    setup_lines.push(format!("{} = File.read(\"{}\").bytes", arg.name, s));
1301                } else if is_base64(s) {
1302                    // Base64: decode it
1303                    setup_lines.push(format!("{} = Base64.decode64(\"{}\").bytes", arg.name, s));
1304                } else {
1305                    // Inline text: encode to binary and convert to bytes array
1306                    let escaped = ruby_string_literal(s);
1307                    setup_lines.push(format!("{} = {}.b.bytes", arg.name, escaped));
1308                }
1309                parts.push(arg.name.clone());
1310            } else {
1311                parts.push("nil".to_string());
1312            }
1313            continue;
1314        }
1315
1316        // Handle file_path arguments: pass the path string as-is
1317        if arg.arg_type == "file_path" {
1318            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1319            for _ in 0..skipped_optional_count {
1320                parts.push("nil".to_string());
1321            }
1322            skipped_optional_count = 0;
1323            let resolved = resolve_field(input, &arg.field);
1324            if let Some(s) = resolved.as_str() {
1325                let escaped = ruby_string_literal(s);
1326                parts.push(escaped);
1327            } else if arg.optional {
1328                skipped_optional_count += 1;
1329                continue;
1330            } else {
1331                parts.push("''".to_string());
1332            }
1333            continue;
1334        }
1335
1336        if arg.arg_type == "handle" {
1337            // Flush any pending nil placeholders for skipped optionals before this positional arg.
1338            for _ in 0..skipped_optional_count {
1339                parts.push("nil".to_string());
1340            }
1341            skipped_optional_count = 0;
1342            // Generate a create_engine (or equivalent) call and pass the variable.
1343            let constructor_name = format!("create_{}", arg.name.to_snake_case());
1344            let config_value = resolve_field(input, &arg.field);
1345            if config_value.is_null()
1346                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1347            {
1348                setup_lines.push(format!("{} = {call_receiver}.{constructor_name}(nil)", arg.name,));
1349            } else {
1350                let literal = json_to_ruby(config_value);
1351                let name = &arg.name;
1352                setup_lines.push(format!("{name}_config = {literal}"));
1353                setup_lines.push(format!(
1354                    "{} = {call_receiver}.{constructor_name}({name}_config.to_json)",
1355                    arg.name,
1356                    name = name,
1357                ));
1358            }
1359            parts.push(arg.name.clone());
1360            continue;
1361        }
1362
1363        let resolved = resolve_field(input, &arg.field);
1364        let val = if resolved.is_null() { None } else { Some(resolved) };
1365        match val {
1366            None | Some(serde_json::Value::Null) if arg.optional => {
1367                // Optional arg with no fixture value: defer; emit nil only if a later arg is present.
1368                skipped_optional_count += 1;
1369                continue;
1370            }
1371            None | Some(serde_json::Value::Null) => {
1372                // Required arg with no fixture value: flush deferred nils, then pass a default.
1373                for _ in 0..skipped_optional_count {
1374                    parts.push("nil".to_string());
1375                }
1376                skipped_optional_count = 0;
1377                let default_val = match arg.arg_type.as_str() {
1378                    "string" => "''".to_string(),
1379                    "int" | "integer" => "0".to_string(),
1380                    "float" | "number" => "0.0".to_string(),
1381                    "bool" | "boolean" => "false".to_string(),
1382                    _ => "nil".to_string(),
1383                };
1384                parts.push(default_val);
1385            }
1386            Some(v) => {
1387                // Flush deferred nil placeholders for skipped optional args that precede this one.
1388                for _ in 0..skipped_optional_count {
1389                    parts.push("nil".to_string());
1390                }
1391                skipped_optional_count = 0;
1392                // For json_object args with options_type, construct a typed options object.
1393                // When result_is_simple, the binding accepts a plain Hash (no wrapper class).
1394                if arg.arg_type == "json_object" && !v.is_null() {
1395                    // Check for batch item arrays (element_type set to BatchBytesItem/BatchFileItem)
1396                    if let Some(elem_type) = &arg.element_type {
1397                        if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && v.is_array() {
1398                            parts.push(emit_ruby_batch_item_array(v, elem_type, module_name));
1399                            continue;
1400                        }
1401                    }
1402                    // Otherwise handle regular options_type objects
1403                    if let (Some(opts_type), Some(obj)) = (options_type, v.as_object()) {
1404                        let kwargs: Vec<String> = obj
1405                            .iter()
1406                            .map(|(k, vv)| {
1407                                let snake_key = k.to_snake_case();
1408                                let rb_val = if enum_fields.contains_key(k) {
1409                                    if let Some(s) = vv.as_str() {
1410                                        let snake_val = s.to_snake_case();
1411                                        format!("'{snake_val}'")
1412                                    } else {
1413                                        json_to_ruby(vv)
1414                                    }
1415                                } else {
1416                                    json_to_ruby(vv)
1417                                };
1418                                format!("{snake_key}: {rb_val}")
1419                            })
1420                            .collect();
1421                        if result_is_simple {
1422                            parts.push(format!("{{{}}}", kwargs.join(", ")));
1423                        } else {
1424                            parts.push(format!("{opts_type}.new({})", kwargs.join(", ")));
1425                        }
1426                        continue;
1427                    }
1428                }
1429                parts.push(json_to_ruby(v));
1430            }
1431        }
1432    }
1433
1434    (setup_lines, parts.join(", "))
1435}
1436
1437#[allow(clippy::too_many_arguments)]
1438fn render_assertion(
1439    out: &mut String,
1440    assertion: &Assertion,
1441    result_var: &str,
1442    field_resolver: &FieldResolver,
1443    result_is_simple: bool,
1444    e2e_config: &E2eConfig,
1445    fields_enum: &HashSet<String>,
1446    per_call_enum_fields: &HashMap<String, String>,
1447) {
1448    // For simple-result methods (e.g. `speech` returning bytes), every field-based
1449    // assertion targets the result itself — there's no struct to access. Drop
1450    // length-only assertions onto the result directly and skip anything else.
1451    if result_is_simple {
1452        if let Some(f) = &assertion.field {
1453            if !f.is_empty() {
1454                match assertion.assertion_type.as_str() {
1455                    "not_empty" => {
1456                        out.push_str(&format!("    expect({result_var}.to_s).not_to be_empty\n"));
1457                        return;
1458                    }
1459                    "is_empty" => {
1460                        out.push_str(&format!("    expect({result_var}.to_s).to be_empty\n"));
1461                        return;
1462                    }
1463                    "count_equals" => {
1464                        if let Some(val) = &assertion.value {
1465                            let rb_val = json_to_ruby(val);
1466                            out.push_str(&format!("    expect({result_var}.length).to eq({rb_val})\n"));
1467                        }
1468                        return;
1469                    }
1470                    "count_min" => {
1471                        if let Some(val) = &assertion.value {
1472                            let rb_val = json_to_ruby(val);
1473                            out.push_str(&format!("    expect({result_var}.length).to be >= {rb_val}\n"));
1474                        }
1475                        return;
1476                    }
1477                    _ => {
1478                        out.push_str(&format!(
1479                            "    # skipped: field '{f}' not applicable for simple result type\n"
1480                        ));
1481                        return;
1482                    }
1483                }
1484            }
1485        }
1486    }
1487    // Handle synthetic / derived fields before the is_valid_for_result check
1488    // so they are never treated as struct attribute accesses on the result.
1489    if let Some(f) = &assertion.field {
1490        match f.as_str() {
1491            "chunks_have_content" => {
1492                let pred = format!("({result_var}.chunks || []).all? {{ |c| c.content && !c.content.empty? }}");
1493                match assertion.assertion_type.as_str() {
1494                    "is_true" => {
1495                        out.push_str(&format!("    expect({pred}).to be(true)\n"));
1496                    }
1497                    "is_false" => {
1498                        out.push_str(&format!("    expect({pred}).to be(false)\n"));
1499                    }
1500                    _ => {
1501                        out.push_str(&format!(
1502                            "    # skipped: unsupported assertion type on synthetic field '{f}'\n"
1503                        ));
1504                    }
1505                }
1506                return;
1507            }
1508            "chunks_have_embeddings" => {
1509                let pred =
1510                    format!("({result_var}.chunks || []).all? {{ |c| !c.embedding.nil? && !c.embedding.empty? }}");
1511                match assertion.assertion_type.as_str() {
1512                    "is_true" => {
1513                        out.push_str(&format!("    expect({pred}).to be(true)\n"));
1514                    }
1515                    "is_false" => {
1516                        out.push_str(&format!("    expect({pred}).to be(false)\n"));
1517                    }
1518                    _ => {
1519                        out.push_str(&format!(
1520                            "    # skipped: unsupported assertion type on synthetic field '{f}'\n"
1521                        ));
1522                    }
1523                }
1524                return;
1525            }
1526            // ---- EmbedResponse virtual fields ----
1527            // embed_texts returns Array<Array<Float>> in Ruby — no wrapper struct.
1528            // result_var is the embedding matrix; use it directly.
1529            "embeddings" => {
1530                match assertion.assertion_type.as_str() {
1531                    "count_equals" => {
1532                        if let Some(val) = &assertion.value {
1533                            let rb_val = json_to_ruby(val);
1534                            out.push_str(&format!("    expect({result_var}.length).to eq({rb_val})\n"));
1535                        }
1536                    }
1537                    "count_min" => {
1538                        if let Some(val) = &assertion.value {
1539                            let rb_val = json_to_ruby(val);
1540                            out.push_str(&format!("    expect({result_var}.length).to be >= {rb_val}\n"));
1541                        }
1542                    }
1543                    "not_empty" => {
1544                        out.push_str(&format!("    expect({result_var}).not_to be_empty\n"));
1545                    }
1546                    "is_empty" => {
1547                        out.push_str(&format!("    expect({result_var}).to be_empty\n"));
1548                    }
1549                    _ => {
1550                        out.push_str("    # skipped: unsupported assertion type on synthetic field 'embeddings'\n");
1551                    }
1552                }
1553                return;
1554            }
1555            "embedding_dimensions" => {
1556                let expr = format!("({result_var}.empty? ? 0 : {result_var}[0].length)");
1557                match assertion.assertion_type.as_str() {
1558                    "equals" => {
1559                        if let Some(val) = &assertion.value {
1560                            let rb_val = json_to_ruby(val);
1561                            out.push_str(&format!("    expect({expr}).to eq({rb_val})\n"));
1562                        }
1563                    }
1564                    "greater_than" => {
1565                        if let Some(val) = &assertion.value {
1566                            let rb_val = json_to_ruby(val);
1567                            out.push_str(&format!("    expect({expr}).to be > {rb_val}\n"));
1568                        }
1569                    }
1570                    _ => {
1571                        out.push_str(
1572                            "    # skipped: unsupported assertion type on synthetic field 'embedding_dimensions'\n",
1573                        );
1574                    }
1575                }
1576                return;
1577            }
1578            "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1579                let pred = match f.as_str() {
1580                    "embeddings_valid" => {
1581                        format!("{result_var}.all? {{ |e| !e.empty? }}")
1582                    }
1583                    "embeddings_finite" => {
1584                        format!("{result_var}.all? {{ |e| e.all? {{ |v| v.finite? }} }}")
1585                    }
1586                    "embeddings_non_zero" => {
1587                        format!("{result_var}.all? {{ |e| e.any? {{ |v| v != 0.0 }} }}")
1588                    }
1589                    "embeddings_normalized" => {
1590                        format!("{result_var}.all? {{ |e| n = e.sum {{ |v| v * v }}; (n - 1.0).abs < 1e-3 }}")
1591                    }
1592                    _ => unreachable!(),
1593                };
1594                match assertion.assertion_type.as_str() {
1595                    "is_true" => {
1596                        out.push_str(&format!("    expect({pred}).to be(true)\n"));
1597                    }
1598                    "is_false" => {
1599                        out.push_str(&format!("    expect({pred}).to be(false)\n"));
1600                    }
1601                    _ => {
1602                        out.push_str(&format!(
1603                            "    # skipped: unsupported assertion type on synthetic field '{f}'\n"
1604                        ));
1605                    }
1606                }
1607                return;
1608            }
1609            // ---- keywords / keywords_count ----
1610            // Ruby ExtractionResult does not expose extracted_keywords; skip.
1611            "keywords" | "keywords_count" => {
1612                out.push_str(&format!(
1613                    "    # skipped: field '{f}' not available on Ruby ExtractionResult\n"
1614                ));
1615                return;
1616            }
1617            _ => {}
1618        }
1619    }
1620
1621    // Skip assertions on fields that don't exist on the result type.
1622    if let Some(f) = &assertion.field {
1623        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1624            out.push_str(&format!("    # skipped: field '{f}' not available on result type\n"));
1625            return;
1626        }
1627    }
1628
1629    // When result_is_simple, skip assertions that reference non-content fields.
1630    if result_is_simple {
1631        if let Some(f) = &assertion.field {
1632            let f_lower = f.to_lowercase();
1633            if !f.is_empty()
1634                && f_lower != "content"
1635                && (f_lower.starts_with("metadata")
1636                    || f_lower.starts_with("document")
1637                    || f_lower.starts_with("structure"))
1638            {
1639                return;
1640            }
1641        }
1642    }
1643
1644    // result_is_simple: treat the result itself as the content string, but only
1645    // when there is no explicit field (or the field is "content"). Count/length
1646    // assertions on named fields (e.g. "warnings") must still walk the field path.
1647    let field_expr = match &assertion.field {
1648        Some(f) if !f.is_empty() && (!result_is_simple || !f.eq_ignore_ascii_case("content")) => {
1649            field_resolver.accessor(f, "ruby", result_var)
1650        }
1651        _ => result_var.to_string(),
1652    };
1653
1654    // For string equality, strip trailing whitespace to handle trailing newlines
1655    // from the converter. Ruby enum fields (Magnus binds Rust enums as Symbols),
1656    // are coerced to String via .to_s so `eq("stop")` matches `:stop`. Look up the
1657    // field in both the global `[crates.e2e] fields_enum` set AND the per-call
1658    // override `[crates.e2e.calls.<x>.overrides.<lang>] enum_fields = { ... }` —
1659    // downstream config that already labels e.g. `status = "BatchStatus"` for the
1660    // Java/C#/Python sides should apply here too without a Ruby-only duplicate.
1661    let field_is_enum = assertion.field.as_deref().filter(|f| !f.is_empty()).is_some_and(|f| {
1662        let resolved = field_resolver.resolve(f);
1663        fields_enum.contains(f)
1664            || fields_enum.contains(resolved)
1665            || per_call_enum_fields.contains_key(f)
1666            || per_call_enum_fields.contains_key(resolved)
1667    });
1668    // For string equality on simple-result calls we want `.to_s.strip` to absorb
1669    // trailing whitespace, but for numeric/bool simple results that coercion turns
1670    // `0` into `"0"` and the `eq(0)` Integer comparison fails. Only fold `.to_s.strip`
1671    // into the simple-result path when the expected value is a string; otherwise
1672    // keep the raw expression so numeric/bool comparisons stay typed.
1673    let expected_is_string = assertion.value.as_ref().is_some_and(|v| v.is_string());
1674    let stripped_field_expr = if result_is_simple && expected_is_string {
1675        format!("{field_expr}.to_s.strip")
1676    } else if field_is_enum {
1677        format!("{field_expr}.to_s")
1678    } else {
1679        field_expr.clone()
1680    };
1681
1682    // Detect whether the assertion field resolves to an array type so that
1683    // contains assertions can iterate items instead of calling .to_s on the array.
1684    let field_is_array = assertion
1685        .field
1686        .as_deref()
1687        .filter(|f| !f.is_empty())
1688        .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1689
1690    match assertion.assertion_type.as_str() {
1691        "equals" => {
1692            if let Some(expected) = &assertion.value {
1693                let is_boolean_val = expected.as_bool().is_some();
1694                let bool_val = expected
1695                    .as_bool()
1696                    .map(|b| if b { "true" } else { "false" })
1697                    .unwrap_or("");
1698                let rb_val = json_to_ruby(expected);
1699                // Mirror Python's `expr.strip() == expected.strip()` pattern when comparing
1700                // string values: converters commonly emit a trailing newline that fixture
1701                // authors don't write into the expected string.
1702                let cmp_expr = if expected.is_string() && !field_is_enum {
1703                    format!("{stripped_field_expr}.to_s.strip")
1704                } else {
1705                    stripped_field_expr.clone()
1706                };
1707                let cmp_expected = if expected.is_string() && !field_is_enum {
1708                    format!("{rb_val}.strip")
1709                } else {
1710                    rb_val
1711                };
1712
1713                let rendered = crate::template_env::render(
1714                    "ruby/assertion.jinja",
1715                    minijinja::context! {
1716                        assertion_type => "equals",
1717                        stripped_field_expr => cmp_expr,
1718                        is_boolean_val => is_boolean_val,
1719                        bool_val => bool_val,
1720                        expected_val => cmp_expected,
1721                    },
1722                );
1723                out.push_str(&rendered);
1724            }
1725        }
1726        "contains" => {
1727            if let Some(expected) = &assertion.value {
1728                let rb_val = json_to_ruby(expected);
1729                let rendered = crate::template_env::render(
1730                    "ruby/assertion.jinja",
1731                    minijinja::context! {
1732                        assertion_type => "contains",
1733                        field_expr => field_expr.clone(),
1734                        field_is_array => field_is_array && expected.is_string(),
1735                        expected_val => rb_val,
1736                    },
1737                );
1738                out.push_str(&rendered);
1739            }
1740        }
1741        "contains_all" => {
1742            if let Some(values) = &assertion.values {
1743                let values_list: Vec<String> = values.iter().map(json_to_ruby).collect();
1744                let rendered = crate::template_env::render(
1745                    "ruby/assertion.jinja",
1746                    minijinja::context! {
1747                        assertion_type => "contains_all",
1748                        field_expr => field_expr.clone(),
1749                        field_is_array => field_is_array,
1750                        values_list => values_list,
1751                    },
1752                );
1753                out.push_str(&rendered);
1754            }
1755        }
1756        "not_contains" => {
1757            if let Some(expected) = &assertion.value {
1758                let rb_val = json_to_ruby(expected);
1759                let rendered = crate::template_env::render(
1760                    "ruby/assertion.jinja",
1761                    minijinja::context! {
1762                        assertion_type => "not_contains",
1763                        field_expr => field_expr.clone(),
1764                        field_is_array => field_is_array && expected.is_string(),
1765                        expected_val => rb_val,
1766                    },
1767                );
1768                out.push_str(&rendered);
1769            }
1770        }
1771        "not_empty" => {
1772            let rendered = crate::template_env::render(
1773                "ruby/assertion.jinja",
1774                minijinja::context! {
1775                    assertion_type => "not_empty",
1776                    field_expr => field_expr.clone(),
1777                },
1778            );
1779            out.push_str(&rendered);
1780        }
1781        "is_empty" => {
1782            let rendered = crate::template_env::render(
1783                "ruby/assertion.jinja",
1784                minijinja::context! {
1785                    assertion_type => "is_empty",
1786                    field_expr => field_expr.clone(),
1787                },
1788            );
1789            out.push_str(&rendered);
1790        }
1791        "contains_any" => {
1792            if let Some(values) = &assertion.values {
1793                let items: Vec<String> = values.iter().map(json_to_ruby).collect();
1794                let rendered = crate::template_env::render(
1795                    "ruby/assertion.jinja",
1796                    minijinja::context! {
1797                        assertion_type => "contains_any",
1798                        field_expr => field_expr.clone(),
1799                        values_list => items,
1800                    },
1801                );
1802                out.push_str(&rendered);
1803            }
1804        }
1805        "greater_than" => {
1806            if let Some(val) = &assertion.value {
1807                let rb_val = json_to_ruby(val);
1808                let rendered = crate::template_env::render(
1809                    "ruby/assertion.jinja",
1810                    minijinja::context! {
1811                        assertion_type => "greater_than",
1812                        field_expr => field_expr.clone(),
1813                        expected_val => rb_val,
1814                    },
1815                );
1816                out.push_str(&rendered);
1817            }
1818        }
1819        "less_than" => {
1820            if let Some(val) = &assertion.value {
1821                let rb_val = json_to_ruby(val);
1822                let rendered = crate::template_env::render(
1823                    "ruby/assertion.jinja",
1824                    minijinja::context! {
1825                        assertion_type => "less_than",
1826                        field_expr => field_expr.clone(),
1827                        expected_val => rb_val,
1828                    },
1829                );
1830                out.push_str(&rendered);
1831            }
1832        }
1833        "greater_than_or_equal" => {
1834            if let Some(val) = &assertion.value {
1835                let rb_val = json_to_ruby(val);
1836                let rendered = crate::template_env::render(
1837                    "ruby/assertion.jinja",
1838                    minijinja::context! {
1839                        assertion_type => "greater_than_or_equal",
1840                        field_expr => field_expr.clone(),
1841                        expected_val => rb_val,
1842                    },
1843                );
1844                out.push_str(&rendered);
1845            }
1846        }
1847        "less_than_or_equal" => {
1848            if let Some(val) = &assertion.value {
1849                let rb_val = json_to_ruby(val);
1850                let rendered = crate::template_env::render(
1851                    "ruby/assertion.jinja",
1852                    minijinja::context! {
1853                        assertion_type => "less_than_or_equal",
1854                        field_expr => field_expr.clone(),
1855                        expected_val => rb_val,
1856                    },
1857                );
1858                out.push_str(&rendered);
1859            }
1860        }
1861        "starts_with" => {
1862            if let Some(expected) = &assertion.value {
1863                let rb_val = json_to_ruby(expected);
1864                let rendered = crate::template_env::render(
1865                    "ruby/assertion.jinja",
1866                    minijinja::context! {
1867                        assertion_type => "starts_with",
1868                        field_expr => field_expr.clone(),
1869                        expected_val => rb_val,
1870                    },
1871                );
1872                out.push_str(&rendered);
1873            }
1874        }
1875        "ends_with" => {
1876            if let Some(expected) = &assertion.value {
1877                let rb_val = json_to_ruby(expected);
1878                let rendered = crate::template_env::render(
1879                    "ruby/assertion.jinja",
1880                    minijinja::context! {
1881                        assertion_type => "ends_with",
1882                        field_expr => field_expr.clone(),
1883                        expected_val => rb_val,
1884                    },
1885                );
1886                out.push_str(&rendered);
1887            }
1888        }
1889        "min_length" | "max_length" | "count_min" | "count_equals" => {
1890            if let Some(val) = &assertion.value {
1891                if let Some(n) = val.as_u64() {
1892                    let rendered = crate::template_env::render(
1893                        "ruby/assertion.jinja",
1894                        minijinja::context! {
1895                            assertion_type => assertion.assertion_type.as_str(),
1896                            field_expr => field_expr.clone(),
1897                            check_n => n,
1898                        },
1899                    );
1900                    out.push_str(&rendered);
1901                }
1902            }
1903        }
1904        "is_true" => {
1905            let rendered = crate::template_env::render(
1906                "ruby/assertion.jinja",
1907                minijinja::context! {
1908                    assertion_type => "is_true",
1909                    field_expr => field_expr.clone(),
1910                },
1911            );
1912            out.push_str(&rendered);
1913        }
1914        "is_false" => {
1915            let rendered = crate::template_env::render(
1916                "ruby/assertion.jinja",
1917                minijinja::context! {
1918                    assertion_type => "is_false",
1919                    field_expr => field_expr.clone(),
1920                },
1921            );
1922            out.push_str(&rendered);
1923        }
1924        "method_result" => {
1925            if let Some(method_name) = &assertion.method {
1926                // Derive call_receiver for module-level helper calls.
1927                let lang = "ruby";
1928                let call = &e2e_config.call;
1929                let overrides = call.overrides.get(lang);
1930                let module_path = overrides
1931                    .and_then(|o| o.module.as_ref())
1932                    .cloned()
1933                    .unwrap_or_else(|| call.module.clone());
1934                let call_receiver = ruby_module_name(&module_path);
1935
1936                let call_expr =
1937                    build_ruby_method_call(&call_receiver, result_var, method_name, assertion.args.as_ref());
1938                let check = assertion.check.as_deref().unwrap_or("is_true");
1939
1940                let (check_val_str, is_boolean_check, bool_check_val, check_n_val) = match check {
1941                    "equals" => {
1942                        if let Some(val) = &assertion.value {
1943                            let is_bool = val.as_bool().is_some();
1944                            let bool_str = val.as_bool().map(|b| if b { "true" } else { "false" }).unwrap_or("");
1945                            let rb_val = json_to_ruby(val);
1946                            (rb_val, is_bool, bool_str.to_string(), 0)
1947                        } else {
1948                            (String::new(), false, String::new(), 0)
1949                        }
1950                    }
1951                    "greater_than_or_equal" => {
1952                        if let Some(val) = &assertion.value {
1953                            (json_to_ruby(val), false, String::new(), 0)
1954                        } else {
1955                            (String::new(), false, String::new(), 0)
1956                        }
1957                    }
1958                    "count_min" => {
1959                        if let Some(val) = &assertion.value {
1960                            let n = val.as_u64().unwrap_or(0);
1961                            (String::new(), false, String::new(), n)
1962                        } else {
1963                            (String::new(), false, String::new(), 0)
1964                        }
1965                    }
1966                    "contains" => {
1967                        if let Some(val) = &assertion.value {
1968                            (json_to_ruby(val), false, String::new(), 0)
1969                        } else {
1970                            (String::new(), false, String::new(), 0)
1971                        }
1972                    }
1973                    _ => (String::new(), false, String::new(), 0),
1974                };
1975
1976                let rendered = crate::template_env::render(
1977                    "ruby/assertion.jinja",
1978                    minijinja::context! {
1979                        assertion_type => "method_result",
1980                        call_expr => call_expr,
1981                        check => check,
1982                        check_val => check_val_str,
1983                        is_boolean_check => is_boolean_check,
1984                        bool_check_val => bool_check_val,
1985                        check_n => check_n_val,
1986                    },
1987                );
1988                out.push_str(&rendered);
1989            } else {
1990                panic!("Ruby e2e generator: method_result assertion missing 'method' field");
1991            }
1992        }
1993        "matches_regex" => {
1994            if let Some(expected) = &assertion.value {
1995                let rb_val = json_to_ruby(expected);
1996                let rendered = crate::template_env::render(
1997                    "ruby/assertion.jinja",
1998                    minijinja::context! {
1999                        assertion_type => "matches_regex",
2000                        field_expr => field_expr.clone(),
2001                        expected_val => rb_val,
2002                    },
2003                );
2004                out.push_str(&rendered);
2005            }
2006        }
2007        "not_error" => {
2008            // Already handled by the call succeeding without exception.
2009        }
2010        "error" => {
2011            // Handled at the example level.
2012        }
2013        other => {
2014            panic!("Ruby e2e generator: unsupported assertion type: {other}");
2015        }
2016    }
2017}
2018
2019/// Build a Ruby call expression for a `method_result` assertion on a tree-sitter Tree.
2020/// Maps method names to the appropriate Ruby method or module-function calls.
2021fn build_ruby_method_call(
2022    call_receiver: &str,
2023    result_var: &str,
2024    method_name: &str,
2025    args: Option<&serde_json::Value>,
2026) -> String {
2027    match method_name {
2028        "root_child_count" => format!("{result_var}.root_node.child_count"),
2029        "root_node_type" => format!("{result_var}.root_node.type"),
2030        "named_children_count" => format!("{result_var}.root_node.named_child_count"),
2031        "has_error_nodes" => format!("{call_receiver}.tree_has_error_nodes({result_var})"),
2032        "error_count" | "tree_error_count" => format!("{call_receiver}.tree_error_count({result_var})"),
2033        "tree_to_sexp" => format!("{call_receiver}.tree_to_sexp({result_var})"),
2034        "contains_node_type" => {
2035            let node_type = args
2036                .and_then(|a| a.get("node_type"))
2037                .and_then(|v| v.as_str())
2038                .unwrap_or("");
2039            format!("{call_receiver}.tree_contains_node_type({result_var}, \"{node_type}\")")
2040        }
2041        "find_nodes_by_type" => {
2042            let node_type = args
2043                .and_then(|a| a.get("node_type"))
2044                .and_then(|v| v.as_str())
2045                .unwrap_or("");
2046            format!("{call_receiver}.find_nodes_by_type({result_var}, \"{node_type}\")")
2047        }
2048        "run_query" => {
2049            let query_source = args
2050                .and_then(|a| a.get("query_source"))
2051                .and_then(|v| v.as_str())
2052                .unwrap_or("");
2053            let language = args
2054                .and_then(|a| a.get("language"))
2055                .and_then(|v| v.as_str())
2056                .unwrap_or("");
2057            format!("{call_receiver}.run_query({result_var}, \"{language}\", \"{query_source}\", source)")
2058        }
2059        _ => format!("{result_var}.{method_name}"),
2060    }
2061}
2062
2063/// Convert a module path (e.g., "html_to_markdown") to Ruby PascalCase module name
2064/// (e.g., "HtmlToMarkdown").
2065fn ruby_module_name(module_path: &str) -> String {
2066    use heck::ToUpperCamelCase;
2067    module_path.to_upper_camel_case()
2068}
2069
2070/// Convert a `serde_json::Value` to a Ruby literal string, preferring single quotes.
2071fn json_to_ruby(value: &serde_json::Value) -> String {
2072    match value {
2073        serde_json::Value::String(s) => ruby_string_literal(s),
2074        serde_json::Value::Bool(true) => "true".to_string(),
2075        serde_json::Value::Bool(false) => "false".to_string(),
2076        serde_json::Value::Number(n) => n.to_string(),
2077        serde_json::Value::Null => "nil".to_string(),
2078        serde_json::Value::Array(arr) => {
2079            let items: Vec<String> = arr.iter().map(json_to_ruby).collect();
2080            format!("[{}]", items.join(", "))
2081        }
2082        serde_json::Value::Object(map) => {
2083            let items: Vec<String> = map
2084                .iter()
2085                .map(|(k, v)| format!("{} => {}", ruby_string_literal(k), json_to_ruby(v)))
2086                .collect();
2087            format!("{{ {} }}", items.join(", "))
2088        }
2089    }
2090}
2091
2092// ---------------------------------------------------------------------------
2093// Visitor generation
2094// ---------------------------------------------------------------------------
2095
2096/// Build a Ruby visitor object and add setup lines. Returns the visitor expression.
2097fn build_ruby_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) -> String {
2098    setup_lines.push("visitor = Class.new do".to_string());
2099    for (method_name, action) in &visitor_spec.callbacks {
2100        emit_ruby_visitor_method(setup_lines, method_name, action);
2101    }
2102    setup_lines.push("end.new".to_string());
2103    "visitor".to_string()
2104}
2105
2106/// Emit a Ruby visitor method for a callback action.
2107fn emit_ruby_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
2108    let params = match method_name {
2109        "visit_link" => "ctx, href, text, title",
2110        "visit_image" => "ctx, src, alt, title",
2111        "visit_heading" => "ctx, level, text, id",
2112        "visit_code_block" => "ctx, lang, code",
2113        "visit_code_inline"
2114        | "visit_strong"
2115        | "visit_emphasis"
2116        | "visit_strikethrough"
2117        | "visit_underline"
2118        | "visit_subscript"
2119        | "visit_superscript"
2120        | "visit_mark"
2121        | "visit_button"
2122        | "visit_summary"
2123        | "visit_figcaption"
2124        | "visit_definition_term"
2125        | "visit_definition_description" => "ctx, text",
2126        "visit_text" => "ctx, text",
2127        "visit_list_item" => "ctx, ordered, marker, text",
2128        "visit_blockquote" => "ctx, content, depth",
2129        "visit_table_row" => "ctx, cells, is_header",
2130        "visit_custom_element" => "ctx, tag_name, html",
2131        "visit_form" => "ctx, action_url, method",
2132        "visit_input" => "ctx, input_type, name, value",
2133        "visit_audio" | "visit_video" | "visit_iframe" => "ctx, src",
2134        "visit_details" => "ctx, is_open",
2135        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "ctx, output",
2136        "visit_list_start" => "ctx, ordered",
2137        "visit_list_end" => "ctx, ordered, output",
2138        _ => "ctx",
2139    };
2140
2141    // Pre-compute action type and values
2142    let (action_type, action_value, return_form) = match action {
2143        CallbackAction::Skip => ("skip", String::new(), "dict"),
2144        CallbackAction::Continue => ("continue", String::new(), "dict"),
2145        CallbackAction::PreserveHtml => ("preserve_html", String::new(), "dict"),
2146        CallbackAction::Custom { output } => {
2147            let escaped = ruby_string_literal(output);
2148            ("custom", escaped, "dict")
2149        }
2150        CallbackAction::CustomTemplate { template, return_form } => {
2151            let interpolated = ruby_template_to_interpolation(template);
2152            let form = match return_form {
2153                TemplateReturnForm::Dict => "dict",
2154                TemplateReturnForm::BareString => "bare_string",
2155            };
2156            ("custom_template", format!("\"{interpolated}\""), form)
2157        }
2158    };
2159
2160    let rendered = crate::template_env::render(
2161        "ruby/visitor_method.jinja",
2162        minijinja::context! {
2163            method_name => method_name,
2164            params => params,
2165            action_type => action_type,
2166            action_value => action_value,
2167            return_form => return_form,
2168        },
2169    );
2170    for line in rendered.lines() {
2171        setup_lines.push(line.to_string());
2172    }
2173}
2174
2175/// Classify a fixture string value that maps to a `bytes` argument.
2176///
2177/// Returns true if the value looks like a file path (e.g. "pdf/fake_memo.pdf").
2178/// File paths have the pattern: alphanumeric/something.extension
2179fn is_file_path(s: &str) -> bool {
2180    if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2181        return false;
2182    }
2183
2184    let first = s.chars().next().unwrap_or('\0');
2185    if first.is_ascii_alphanumeric() || first == '_' {
2186        if let Some(slash_pos) = s.find('/') {
2187            if slash_pos > 0 {
2188                let after_slash = &s[slash_pos + 1..];
2189                if after_slash.contains('.') && !after_slash.is_empty() {
2190                    return true;
2191                }
2192            }
2193        }
2194    }
2195
2196    false
2197}
2198
2199/// Check if a string looks like base64-encoded data.
2200/// If it's not a file path or inline text, assume it's base64.
2201fn is_base64(s: &str) -> bool {
2202    if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
2203        return false;
2204    }
2205
2206    if is_file_path(s) {
2207        return false;
2208    }
2209
2210    true
2211}