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::config::E2eConfig;
7use crate::escape::{ruby_string_literal, sanitize_filename, sanitize_ident};
8use crate::field_access::FieldResolver;
9use crate::fixture::{Assertion, Fixture, FixtureGroup};
10use alef_core::backend::GeneratedFile;
11use alef_core::config::AlefConfig;
12use anyhow::Result;
13use heck::ToSnakeCase;
14use std::collections::HashMap;
15use std::fmt::Write as FmtWrite;
16use std::path::PathBuf;
17
18use super::E2eCodegen;
19
20/// Ruby e2e code generator.
21pub struct RubyCodegen;
22
23impl E2eCodegen for RubyCodegen {
24    fn generate(
25        &self,
26        groups: &[FixtureGroup],
27        e2e_config: &E2eConfig,
28        alef_config: &AlefConfig,
29    ) -> Result<Vec<GeneratedFile>> {
30        let lang = self.language_name();
31        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
32
33        let mut files = Vec::new();
34
35        // Resolve call config with overrides.
36        let call = &e2e_config.call;
37        let overrides = call.overrides.get(lang);
38        let module_path = overrides
39            .and_then(|o| o.module.as_ref())
40            .cloned()
41            .unwrap_or_else(|| call.module.clone());
42        let function_name = overrides
43            .and_then(|o| o.function.as_ref())
44            .cloned()
45            .unwrap_or_else(|| call.function.clone());
46        let class_name = overrides.and_then(|o| o.class.as_ref()).cloned();
47        let options_type = overrides.and_then(|o| o.options_type.clone());
48        let empty_enum_fields = HashMap::new();
49        let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields);
50        let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
51        let result_var = &call.result_var;
52
53        // Resolve package config.
54        let ruby_pkg = e2e_config.resolve_package("ruby");
55        let gem_name = ruby_pkg
56            .as_ref()
57            .and_then(|p| p.name.as_ref())
58            .cloned()
59            .unwrap_or_else(|| alef_config.crate_config.name.replace('-', "_"));
60        let gem_path = ruby_pkg
61            .as_ref()
62            .and_then(|p| p.path.as_ref())
63            .cloned()
64            .unwrap_or_else(|| "../../packages/ruby".to_string());
65        let gem_version = ruby_pkg
66            .as_ref()
67            .and_then(|p| p.version.as_ref())
68            .cloned()
69            .unwrap_or_else(|| "0.1.0".to_string());
70
71        // Generate Gemfile.
72        files.push(GeneratedFile {
73            path: output_base.join("Gemfile"),
74            content: render_gemfile(&gem_name, &gem_path, &gem_version, e2e_config.dep_mode),
75            generated_header: false,
76        });
77
78        // Generate .rubocop.yaml for linting generated specs.
79        files.push(GeneratedFile {
80            path: output_base.join(".rubocop.yaml"),
81            content: render_rubocop_yaml(),
82            generated_header: false,
83        });
84
85        // Generate spec files per category.
86        let spec_base = output_base.join("spec");
87
88        for group in groups {
89            let active: Vec<&Fixture> = group
90                .fixtures
91                .iter()
92                .filter(|f| f.skip.as_ref().is_none_or(|s| !s.should_skip(lang)))
93                .collect();
94
95            if active.is_empty() {
96                continue;
97            }
98
99            let field_resolver_pre = FieldResolver::new(
100                &e2e_config.fields,
101                &e2e_config.fields_optional,
102                &e2e_config.result_fields,
103                &e2e_config.fields_array,
104            );
105            // Skip the entire file if no fixture in this category produces output.
106            let has_any_output = active.iter().any(|f| {
107                let expects_error = f.assertions.iter().any(|a| a.assertion_type == "error");
108                expects_error || has_usable_assertion(f, &field_resolver_pre, result_is_simple)
109            });
110            if !has_any_output {
111                continue;
112            }
113
114            let filename = format!("{}_spec.rb", sanitize_filename(&group.category));
115            let field_resolver = FieldResolver::new(
116                &e2e_config.fields,
117                &e2e_config.fields_optional,
118                &e2e_config.result_fields,
119                &e2e_config.fields_array,
120            );
121            let content = render_spec_file(
122                &group.category,
123                &active,
124                &module_path,
125                &function_name,
126                class_name.as_deref(),
127                result_var,
128                &gem_name,
129                &e2e_config.call.args,
130                &field_resolver,
131                options_type.as_deref(),
132                enum_fields,
133                result_is_simple,
134            );
135            files.push(GeneratedFile {
136                path: spec_base.join(filename),
137                content,
138                generated_header: true,
139            });
140        }
141
142        Ok(files)
143    }
144
145    fn language_name(&self) -> &'static str {
146        "ruby"
147    }
148}
149
150// ---------------------------------------------------------------------------
151// Rendering
152// ---------------------------------------------------------------------------
153
154fn render_gemfile(
155    gem_name: &str,
156    gem_path: &str,
157    gem_version: &str,
158    dep_mode: crate::config::DependencyMode,
159) -> String {
160    let gem_line = match dep_mode {
161        crate::config::DependencyMode::Registry => format!("gem '{gem_name}', '{gem_version}'"),
162        crate::config::DependencyMode::Local => format!("gem '{gem_name}', path: '{gem_path}'"),
163    };
164    format!(
165        "# frozen_string_literal: true\n\
166         \n\
167         source 'https://rubygems.org'\n\
168         \n\
169         {gem_line}\n\
170         gem 'rspec', '~> 3.13'\n\
171         gem 'rubocop', '~> 1.86'\n\
172         gem 'rubocop-rspec', '~> 3.9'\n"
173    )
174}
175
176fn render_rubocop_yaml() -> String {
177    r#"# Generated by alef e2e — do not edit.
178AllCops:
179  NewCops: enable
180  TargetRubyVersion: 3.2
181  SuggestExtensions: false
182
183plugins:
184  - rubocop-rspec
185
186# --- Justified suppressions for generated test code ---
187
188# Generated tests are verbose by nature (setup + multiple assertions).
189Metrics/BlockLength:
190  Enabled: false
191Metrics/MethodLength:
192  Enabled: false
193Layout/LineLength:
194  Enabled: false
195
196# Generated tests use multiple assertions per example for thorough verification.
197RSpec/MultipleExpectations:
198  Enabled: false
199RSpec/ExampleLength:
200  Enabled: false
201
202# Generated tests describe categories as strings, not classes.
203RSpec/DescribeClass:
204  Enabled: false
205
206# Fixture-driven tests may produce identical assertion bodies for different inputs.
207RSpec/RepeatedExample:
208  Enabled: false
209
210# Error-handling tests use bare raise_error (exception type not known at generation time).
211RSpec/UnspecifiedException:
212  Enabled: false
213"#
214    .to_string()
215}
216
217#[allow(clippy::too_many_arguments)]
218fn render_spec_file(
219    category: &str,
220    fixtures: &[&Fixture],
221    module_path: &str,
222    function_name: &str,
223    class_name: Option<&str>,
224    result_var: &str,
225    gem_name: &str,
226    args: &[crate::config::ArgMapping],
227    field_resolver: &FieldResolver,
228    options_type: Option<&str>,
229    enum_fields: &HashMap<String, String>,
230    result_is_simple: bool,
231) -> String {
232    let mut out = String::new();
233    let _ = writeln!(out, "# This file is auto-generated by alef. DO NOT EDIT.");
234    let _ = writeln!(out, "# frozen_string_literal: true");
235    let _ = writeln!(out);
236
237    // Require the gem (single quotes).
238    let require_name = if module_path.is_empty() { gem_name } else { module_path };
239    let _ = writeln!(out, "require '{}'", require_name.replace('-', "_"));
240    let _ = writeln!(out, "require 'json'");
241    let _ = writeln!(out);
242
243    // Build the Ruby module/class qualifier for calls.
244    let call_receiver = class_name
245        .map(|s| s.to_string())
246        .unwrap_or_else(|| ruby_module_name(module_path));
247
248    let _ = writeln!(out, "RSpec.describe '{}' do", category);
249
250    let mut first = true;
251    for fixture in fixtures {
252        if !first {
253            let _ = writeln!(out);
254        }
255        first = false;
256
257        render_example(
258            &mut out,
259            fixture,
260            function_name,
261            &call_receiver,
262            result_var,
263            args,
264            field_resolver,
265            options_type,
266            enum_fields,
267            result_is_simple,
268        );
269    }
270
271    let _ = writeln!(out, "end");
272    out
273}
274
275/// Check if a fixture has at least one assertion that will produce an executable
276/// expect() call (not just a skip comment).
277fn has_usable_assertion(fixture: &Fixture, field_resolver: &FieldResolver, result_is_simple: bool) -> bool {
278    fixture.assertions.iter().any(|a| {
279        // not_error is implicit (call succeeding), error is handled separately.
280        if a.assertion_type == "not_error" || a.assertion_type == "error" {
281            return false;
282        }
283        // Check field validity.
284        if let Some(f) = &a.field {
285            if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
286                return false;
287            }
288            // When result_is_simple, skip non-content fields.
289            if result_is_simple {
290                let f_lower = f.to_lowercase();
291                if !f.is_empty()
292                    && f_lower != "content"
293                    && (f_lower.starts_with("metadata")
294                        || f_lower.starts_with("document")
295                        || f_lower.starts_with("structure"))
296                {
297                    return false;
298                }
299            }
300        }
301        true
302    })
303}
304
305#[allow(clippy::too_many_arguments)]
306fn render_example(
307    out: &mut String,
308    fixture: &Fixture,
309    function_name: &str,
310    call_receiver: &str,
311    result_var: &str,
312    args: &[crate::config::ArgMapping],
313    field_resolver: &FieldResolver,
314    options_type: Option<&str>,
315    enum_fields: &HashMap<String, String>,
316    result_is_simple: bool,
317) {
318    let test_name = sanitize_ident(&fixture.id);
319    let description = fixture.description.replace('\'', "\\'");
320    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
321
322    let (setup_lines, args_str) = build_args_and_setup(
323        &fixture.input,
324        args,
325        call_receiver,
326        options_type,
327        enum_fields,
328        result_is_simple,
329        &fixture.id,
330    );
331
332    let call_expr = format!("{call_receiver}.{function_name}({args_str})");
333
334    let _ = writeln!(out, "  it '{test_name}: {description}' do");
335
336    for line in &setup_lines {
337        let _ = writeln!(out, "    {line}");
338    }
339
340    if expects_error {
341        let _ = writeln!(out, "    expect {{ {call_expr} }}.to raise_error");
342        let _ = writeln!(out, "  end");
343        return;
344    }
345
346    // Check if any non-error assertion actually uses the result variable.
347    let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
348    let _ = writeln!(out, "    {result_var} = {call_expr}");
349
350    for assertion in &fixture.assertions {
351        render_assertion(out, assertion, result_var, field_resolver, result_is_simple);
352    }
353
354    // When all assertions were skipped (fields unavailable), the example has no
355    // expect() calls, which triggers rubocop's RSpec/NoExpectationExample cop.
356    // Emit a minimal placeholder expectation so rubocop is satisfied.
357    if !has_usable {
358        let _ = writeln!(out, "    expect({result_var}).not_to be_nil");
359    }
360
361    let _ = writeln!(out, "  end");
362}
363
364/// Build setup lines (e.g. handle creation) and the argument list for the function call.
365///
366/// Returns `(setup_lines, args_string)`.
367fn build_args_and_setup(
368    input: &serde_json::Value,
369    args: &[crate::config::ArgMapping],
370    call_receiver: &str,
371    options_type: Option<&str>,
372    enum_fields: &HashMap<String, String>,
373    result_is_simple: bool,
374    fixture_id: &str,
375) -> (Vec<String>, String) {
376    if args.is_empty() {
377        return (Vec::new(), json_to_ruby(input));
378    }
379
380    let mut setup_lines: Vec<String> = Vec::new();
381    let mut parts: Vec<String> = Vec::new();
382
383    for arg in args {
384        if arg.arg_type == "mock_url" {
385            setup_lines.push(format!(
386                "{} = \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
387                arg.name,
388            ));
389            parts.push(arg.name.clone());
390            continue;
391        }
392
393        if arg.arg_type == "handle" {
394            // Generate a create_engine (or equivalent) call and pass the variable.
395            let constructor_name = format!("create_{}", arg.name.to_snake_case());
396            let config_value = input.get(&arg.field).unwrap_or(&serde_json::Value::Null);
397            if config_value.is_null()
398                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
399            {
400                setup_lines.push(format!("{} = {call_receiver}.{constructor_name}(nil)", arg.name,));
401            } else {
402                let literal = json_to_ruby(config_value);
403                let name = &arg.name;
404                setup_lines.push(format!("{name}_config = {literal}"));
405                setup_lines.push(format!(
406                    "{} = {call_receiver}.{constructor_name}({name}_config.to_json)",
407                    arg.name,
408                    name = name,
409                ));
410            }
411            parts.push(arg.name.clone());
412            continue;
413        }
414
415        let val = input.get(&arg.field);
416        match val {
417            None | Some(serde_json::Value::Null) if arg.optional => {
418                // Optional arg with no fixture value: skip entirely.
419                continue;
420            }
421            None | Some(serde_json::Value::Null) => {
422                // Required arg with no fixture value: pass a language-appropriate default.
423                let default_val = match arg.arg_type.as_str() {
424                    "string" => "''".to_string(),
425                    "int" | "integer" => "0".to_string(),
426                    "float" | "number" => "0.0".to_string(),
427                    "bool" | "boolean" => "false".to_string(),
428                    _ => "nil".to_string(),
429                };
430                parts.push(default_val);
431            }
432            Some(v) => {
433                // For json_object args with options_type, construct a typed options object.
434                // When result_is_simple, the binding accepts a plain Hash (no wrapper class).
435                if arg.arg_type == "json_object" && !v.is_null() {
436                    if let (Some(opts_type), Some(obj)) = (options_type, v.as_object()) {
437                        let kwargs: Vec<String> = obj
438                            .iter()
439                            .map(|(k, vv)| {
440                                let snake_key = k.to_snake_case();
441                                let rb_val = if enum_fields.contains_key(k) {
442                                    if let Some(s) = vv.as_str() {
443                                        let snake_val = s.to_snake_case();
444                                        format!("'{snake_val}'")
445                                    } else {
446                                        json_to_ruby(vv)
447                                    }
448                                } else {
449                                    json_to_ruby(vv)
450                                };
451                                format!("{snake_key}: {rb_val}")
452                            })
453                            .collect();
454                        if result_is_simple {
455                            parts.push(format!("{{{}}}", kwargs.join(", ")));
456                        } else {
457                            parts.push(format!("{opts_type}.new({})", kwargs.join(", ")));
458                        }
459                        continue;
460                    }
461                }
462                parts.push(json_to_ruby(v));
463            }
464        }
465    }
466
467    (setup_lines, parts.join(", "))
468}
469
470fn render_assertion(
471    out: &mut String,
472    assertion: &Assertion,
473    result_var: &str,
474    field_resolver: &FieldResolver,
475    result_is_simple: bool,
476) {
477    // Skip assertions on fields that don't exist on the result type.
478    if let Some(f) = &assertion.field {
479        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
480            let _ = writeln!(out, "    # skipped: field '{f}' not available on result type");
481            return;
482        }
483    }
484
485    // When result_is_simple, skip assertions that reference non-content fields.
486    if result_is_simple {
487        if let Some(f) = &assertion.field {
488            let f_lower = f.to_lowercase();
489            if !f.is_empty()
490                && f_lower != "content"
491                && (f_lower.starts_with("metadata")
492                    || f_lower.starts_with("document")
493                    || f_lower.starts_with("structure"))
494            {
495                return;
496            }
497        }
498    }
499
500    let field_expr = if result_is_simple {
501        result_var.to_string()
502    } else {
503        match &assertion.field {
504            Some(f) if !f.is_empty() => field_resolver.accessor(f, "ruby", result_var),
505            _ => result_var.to_string(),
506        }
507    };
508
509    // For string equality, strip trailing whitespace to handle trailing newlines
510    // from the converter.
511    let stripped_field_expr = if result_is_simple {
512        format!("{field_expr}.strip")
513    } else {
514        field_expr.clone()
515    };
516
517    match assertion.assertion_type.as_str() {
518        "equals" => {
519            if let Some(expected) = &assertion.value {
520                // Use be(true)/be(false) for booleans (RSpec/BeEq).
521                if let Some(b) = expected.as_bool() {
522                    let _ = writeln!(out, "    expect({stripped_field_expr}).to be({b})");
523                } else {
524                    let rb_val = json_to_ruby(expected);
525                    let _ = writeln!(out, "    expect({stripped_field_expr}).to eq({rb_val})");
526                }
527            }
528        }
529        "contains" => {
530            if let Some(expected) = &assertion.value {
531                let rb_val = json_to_ruby(expected);
532                // Use .to_s to handle both String and Symbol (enum) fields
533                let _ = writeln!(out, "    expect({field_expr}.to_s).to include({rb_val})");
534            }
535        }
536        "contains_all" => {
537            if let Some(values) = &assertion.values {
538                for val in values {
539                    let rb_val = json_to_ruby(val);
540                    let _ = writeln!(out, "    expect({field_expr}.to_s).to include({rb_val})");
541                }
542            }
543        }
544        "not_contains" => {
545            if let Some(expected) = &assertion.value {
546                let rb_val = json_to_ruby(expected);
547                let _ = writeln!(out, "    expect({field_expr}.to_s).not_to include({rb_val})");
548            }
549        }
550        "not_empty" => {
551            let _ = writeln!(out, "    expect({field_expr}).not_to be_empty");
552        }
553        "is_empty" => {
554            // Handle nil (None) as empty for optional fields
555            let _ = writeln!(out, "    expect({field_expr}.nil? || {field_expr}.empty?).to be(true)");
556        }
557        "contains_any" => {
558            if let Some(values) = &assertion.values {
559                let items: Vec<String> = values.iter().map(json_to_ruby).collect();
560                let arr_str = items.join(", ");
561                let _ = writeln!(
562                    out,
563                    "    expect([{arr_str}].any? {{ |v| {field_expr}.to_s.include?(v) }}).to be(true)"
564                );
565            }
566        }
567        "greater_than" => {
568            if let Some(val) = &assertion.value {
569                let rb_val = json_to_ruby(val);
570                let _ = writeln!(out, "    expect({field_expr}).to be > {rb_val}");
571            }
572        }
573        "less_than" => {
574            if let Some(val) = &assertion.value {
575                let rb_val = json_to_ruby(val);
576                let _ = writeln!(out, "    expect({field_expr}).to be < {rb_val}");
577            }
578        }
579        "greater_than_or_equal" => {
580            if let Some(val) = &assertion.value {
581                let rb_val = json_to_ruby(val);
582                let _ = writeln!(out, "    expect({field_expr}).to be >= {rb_val}");
583            }
584        }
585        "less_than_or_equal" => {
586            if let Some(val) = &assertion.value {
587                let rb_val = json_to_ruby(val);
588                let _ = writeln!(out, "    expect({field_expr}).to be <= {rb_val}");
589            }
590        }
591        "starts_with" => {
592            if let Some(expected) = &assertion.value {
593                let rb_val = json_to_ruby(expected);
594                let _ = writeln!(out, "    expect({field_expr}).to start_with({rb_val})");
595            }
596        }
597        "ends_with" => {
598            if let Some(expected) = &assertion.value {
599                let rb_val = json_to_ruby(expected);
600                let _ = writeln!(out, "    expect({field_expr}).to end_with({rb_val})");
601            }
602        }
603        "min_length" => {
604            if let Some(val) = &assertion.value {
605                if let Some(n) = val.as_u64() {
606                    let _ = writeln!(out, "    expect({field_expr}.length).to be >= {n}");
607                }
608            }
609        }
610        "max_length" => {
611            if let Some(val) = &assertion.value {
612                if let Some(n) = val.as_u64() {
613                    let _ = writeln!(out, "    expect({field_expr}.length).to be <= {n}");
614                }
615            }
616        }
617        "count_min" => {
618            if let Some(val) = &assertion.value {
619                if let Some(n) = val.as_u64() {
620                    let _ = writeln!(out, "    expect({field_expr}.length).to be >= {n}");
621                }
622            }
623        }
624        "not_error" => {
625            // Already handled by the call succeeding without exception.
626        }
627        "error" => {
628            // Handled at the example level.
629        }
630        other => {
631            let _ = writeln!(out, "    # TODO: unsupported assertion type: {other}");
632        }
633    }
634}
635
636/// Convert a module path (e.g., "html_to_markdown") to Ruby PascalCase module name
637/// (e.g., "HtmlToMarkdown").
638fn ruby_module_name(module_path: &str) -> String {
639    use heck::ToUpperCamelCase;
640    module_path.to_upper_camel_case()
641}
642
643/// Convert a `serde_json::Value` to a Ruby literal string, preferring single quotes.
644fn json_to_ruby(value: &serde_json::Value) -> String {
645    match value {
646        serde_json::Value::String(s) => ruby_string_literal(s),
647        serde_json::Value::Bool(true) => "true".to_string(),
648        serde_json::Value::Bool(false) => "false".to_string(),
649        serde_json::Value::Number(n) => n.to_string(),
650        serde_json::Value::Null => "nil".to_string(),
651        serde_json::Value::Array(arr) => {
652            let items: Vec<String> = arr.iter().map(json_to_ruby).collect();
653            format!("[{}]", items.join(", "))
654        }
655        serde_json::Value::Object(map) => {
656            let items: Vec<String> = map
657                .iter()
658                .map(|(k, v)| format!("{} => {}", ruby_string_literal(k), json_to_ruby(v)))
659                .collect();
660            format!("{{ {} }}", items.join(", "))
661        }
662    }
663}