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        // Skip examples that have zero usable assertions (no executable expect() calls).
253        // This prevents Lint/UselessAssignment, RSpec/NoExpectationExample,
254        // and RSpec/RepeatedExample.
255        let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
256        if !expects_error && !has_usable_assertion(fixture, field_resolver, result_is_simple) {
257            continue;
258        }
259
260        if !first {
261            let _ = writeln!(out);
262        }
263        first = false;
264
265        render_example(
266            &mut out,
267            fixture,
268            function_name,
269            &call_receiver,
270            result_var,
271            args,
272            field_resolver,
273            options_type,
274            enum_fields,
275            result_is_simple,
276        );
277    }
278
279    let _ = writeln!(out, "end");
280    out
281}
282
283/// Check if a fixture has at least one assertion that will produce an executable
284/// expect() call (not just a skip comment).
285fn has_usable_assertion(fixture: &Fixture, field_resolver: &FieldResolver, result_is_simple: bool) -> bool {
286    fixture.assertions.iter().any(|a| {
287        // not_error is implicit (call succeeding), error is handled separately.
288        if a.assertion_type == "not_error" || a.assertion_type == "error" {
289            return false;
290        }
291        // Check field validity.
292        if let Some(f) = &a.field {
293            if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
294                return false;
295            }
296            // When result_is_simple, skip non-content fields.
297            if result_is_simple {
298                let f_lower = f.to_lowercase();
299                if !f.is_empty()
300                    && f_lower != "content"
301                    && (f_lower.starts_with("metadata")
302                        || f_lower.starts_with("document")
303                        || f_lower.starts_with("structure"))
304                {
305                    return false;
306                }
307            }
308        }
309        true
310    })
311}
312
313#[allow(clippy::too_many_arguments)]
314fn render_example(
315    out: &mut String,
316    fixture: &Fixture,
317    function_name: &str,
318    call_receiver: &str,
319    result_var: &str,
320    args: &[crate::config::ArgMapping],
321    field_resolver: &FieldResolver,
322    options_type: Option<&str>,
323    enum_fields: &HashMap<String, String>,
324    result_is_simple: bool,
325) {
326    let test_name = sanitize_ident(&fixture.id);
327    let description = fixture.description.replace('\'', "\\'");
328    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
329
330    let (setup_lines, args_str) = build_args_and_setup(
331        &fixture.input,
332        args,
333        call_receiver,
334        options_type,
335        enum_fields,
336        result_is_simple,
337        &fixture.id,
338    );
339
340    let call_expr = format!("{call_receiver}.{function_name}({args_str})");
341
342    let _ = writeln!(out, "  it '{test_name}: {description}' do");
343
344    for line in &setup_lines {
345        let _ = writeln!(out, "    {line}");
346    }
347
348    if expects_error {
349        let _ = writeln!(out, "    expect {{ {call_expr} }}.to raise_error");
350        let _ = writeln!(out, "  end");
351        return;
352    }
353
354    // Check if any non-error assertion actually uses the result variable.
355    let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
356    if has_usable {
357        let _ = writeln!(out, "    {result_var} = {call_expr}");
358    } else {
359        let _ = writeln!(out, "    {call_expr}");
360    }
361
362    for assertion in &fixture.assertions {
363        render_assertion(out, assertion, result_var, field_resolver, result_is_simple);
364    }
365
366    let _ = writeln!(out, "  end");
367}
368
369/// Build setup lines (e.g. handle creation) and the argument list for the function call.
370///
371/// Returns `(setup_lines, args_string)`.
372fn build_args_and_setup(
373    input: &serde_json::Value,
374    args: &[crate::config::ArgMapping],
375    call_receiver: &str,
376    options_type: Option<&str>,
377    enum_fields: &HashMap<String, String>,
378    result_is_simple: bool,
379    fixture_id: &str,
380) -> (Vec<String>, String) {
381    if args.is_empty() {
382        return (Vec::new(), json_to_ruby(input));
383    }
384
385    let mut setup_lines: Vec<String> = Vec::new();
386    let mut parts: Vec<String> = Vec::new();
387
388    for arg in args {
389        if arg.arg_type == "mock_url" {
390            setup_lines.push(format!(
391                "{} = \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
392                arg.name,
393            ));
394            parts.push(arg.name.clone());
395            continue;
396        }
397
398        if arg.arg_type == "handle" {
399            // Generate a create_engine (or equivalent) call and pass the variable.
400            let constructor_name = format!("create_{}", arg.name.to_snake_case());
401            let config_value = input.get(&arg.field).unwrap_or(&serde_json::Value::Null);
402            if config_value.is_null()
403                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
404            {
405                setup_lines.push(format!("{} = {call_receiver}.{constructor_name}(nil)", arg.name,));
406            } else {
407                let literal = json_to_ruby(config_value);
408                let name = &arg.name;
409                setup_lines.push(format!("{name}_config = {literal}"));
410                setup_lines.push(format!(
411                    "{} = {call_receiver}.{constructor_name}({name}_config.to_json)",
412                    arg.name,
413                    name = name,
414                ));
415            }
416            parts.push(arg.name.clone());
417            continue;
418        }
419
420        let val = input.get(&arg.field);
421        match val {
422            None | Some(serde_json::Value::Null) if arg.optional => {
423                // Optional arg with no fixture value: skip entirely.
424                continue;
425            }
426            None | Some(serde_json::Value::Null) => {
427                // Required arg with no fixture value: pass a language-appropriate default.
428                let default_val = match arg.arg_type.as_str() {
429                    "string" => "''".to_string(),
430                    "int" | "integer" => "0".to_string(),
431                    "float" | "number" => "0.0".to_string(),
432                    "bool" | "boolean" => "false".to_string(),
433                    _ => "nil".to_string(),
434                };
435                parts.push(default_val);
436            }
437            Some(v) => {
438                // For json_object args with options_type, construct a typed options object.
439                // When result_is_simple, the binding accepts a plain Hash (no wrapper class).
440                if arg.arg_type == "json_object" && !v.is_null() {
441                    if let (Some(opts_type), Some(obj)) = (options_type, v.as_object()) {
442                        let kwargs: Vec<String> = obj
443                            .iter()
444                            .map(|(k, vv)| {
445                                let snake_key = k.to_snake_case();
446                                let rb_val = if enum_fields.contains_key(k) {
447                                    if let Some(s) = vv.as_str() {
448                                        let snake_val = s.to_snake_case();
449                                        format!("'{snake_val}'")
450                                    } else {
451                                        json_to_ruby(vv)
452                                    }
453                                } else {
454                                    json_to_ruby(vv)
455                                };
456                                format!("{snake_key}: {rb_val}")
457                            })
458                            .collect();
459                        if result_is_simple {
460                            parts.push(format!("{{{}}}", kwargs.join(", ")));
461                        } else {
462                            parts.push(format!("{opts_type}.new({})", kwargs.join(", ")));
463                        }
464                        continue;
465                    }
466                }
467                parts.push(json_to_ruby(v));
468            }
469        }
470    }
471
472    (setup_lines, parts.join(", "))
473}
474
475fn render_assertion(
476    out: &mut String,
477    assertion: &Assertion,
478    result_var: &str,
479    field_resolver: &FieldResolver,
480    result_is_simple: bool,
481) {
482    // Skip assertions on fields that don't exist on the result type.
483    if let Some(f) = &assertion.field {
484        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
485            // Don't emit skip comments — the example-level filter ensures we only
486            // get here in mixed cases, and the comment would be noise.
487            return;
488        }
489    }
490
491    // When result_is_simple, skip assertions that reference non-content fields.
492    if result_is_simple {
493        if let Some(f) = &assertion.field {
494            let f_lower = f.to_lowercase();
495            if !f.is_empty()
496                && f_lower != "content"
497                && (f_lower.starts_with("metadata")
498                    || f_lower.starts_with("document")
499                    || f_lower.starts_with("structure"))
500            {
501                return;
502            }
503        }
504    }
505
506    let field_expr = if result_is_simple {
507        result_var.to_string()
508    } else {
509        match &assertion.field {
510            Some(f) if !f.is_empty() => field_resolver.accessor(f, "ruby", result_var),
511            _ => result_var.to_string(),
512        }
513    };
514
515    // For string equality, strip trailing whitespace to handle trailing newlines
516    // from the converter.
517    let stripped_field_expr = if result_is_simple {
518        format!("{field_expr}.strip")
519    } else {
520        field_expr.clone()
521    };
522
523    match assertion.assertion_type.as_str() {
524        "equals" => {
525            if let Some(expected) = &assertion.value {
526                // Use be(true)/be(false) for booleans (RSpec/BeEq).
527                if let Some(b) = expected.as_bool() {
528                    let _ = writeln!(out, "    expect({stripped_field_expr}).to be({b})");
529                } else {
530                    let rb_val = json_to_ruby(expected);
531                    let _ = writeln!(out, "    expect({stripped_field_expr}).to eq({rb_val})");
532                }
533            }
534        }
535        "contains" => {
536            if let Some(expected) = &assertion.value {
537                let rb_val = json_to_ruby(expected);
538                // Use .to_s to handle both String and Symbol (enum) fields
539                let _ = writeln!(out, "    expect({field_expr}.to_s).to include({rb_val})");
540            }
541        }
542        "contains_all" => {
543            if let Some(values) = &assertion.values {
544                for val in values {
545                    let rb_val = json_to_ruby(val);
546                    let _ = writeln!(out, "    expect({field_expr}.to_s).to include({rb_val})");
547                }
548            }
549        }
550        "not_contains" => {
551            if let Some(expected) = &assertion.value {
552                let rb_val = json_to_ruby(expected);
553                let _ = writeln!(out, "    expect({field_expr}.to_s).not_to include({rb_val})");
554            }
555        }
556        "not_empty" => {
557            let _ = writeln!(out, "    expect({field_expr}).not_to be_empty");
558        }
559        "is_empty" => {
560            // Handle nil (None) as empty for optional fields
561            let _ = writeln!(out, "    expect({field_expr}.nil? || {field_expr}.empty?).to be(true)");
562        }
563        "contains_any" => {
564            if let Some(values) = &assertion.values {
565                let items: Vec<String> = values.iter().map(json_to_ruby).collect();
566                let arr_str = items.join(", ");
567                let _ = writeln!(
568                    out,
569                    "    expect([{arr_str}].any? {{ |v| {field_expr}.to_s.include?(v) }}).to be(true)"
570                );
571            }
572        }
573        "greater_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        "less_than" => {
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        "greater_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        "less_than_or_equal" => {
592            if let Some(val) = &assertion.value {
593                let rb_val = json_to_ruby(val);
594                let _ = writeln!(out, "    expect({field_expr}).to be <= {rb_val}");
595            }
596        }
597        "starts_with" => {
598            if let Some(expected) = &assertion.value {
599                let rb_val = json_to_ruby(expected);
600                let _ = writeln!(out, "    expect({field_expr}).to start_with({rb_val})");
601            }
602        }
603        "ends_with" => {
604            if let Some(expected) = &assertion.value {
605                let rb_val = json_to_ruby(expected);
606                let _ = writeln!(out, "    expect({field_expr}).to end_with({rb_val})");
607            }
608        }
609        "min_length" => {
610            if let Some(val) = &assertion.value {
611                if let Some(n) = val.as_u64() {
612                    let _ = writeln!(out, "    expect({field_expr}.length).to be >= {n}");
613                }
614            }
615        }
616        "max_length" => {
617            if let Some(val) = &assertion.value {
618                if let Some(n) = val.as_u64() {
619                    let _ = writeln!(out, "    expect({field_expr}.length).to be <= {n}");
620                }
621            }
622        }
623        "count_min" => {
624            if let Some(val) = &assertion.value {
625                if let Some(n) = val.as_u64() {
626                    let _ = writeln!(out, "    expect({field_expr}.length).to be >= {n}");
627                }
628            }
629        }
630        "not_error" => {
631            // Already handled by the call succeeding without exception.
632        }
633        "error" => {
634            // Handled at the example level.
635        }
636        other => {
637            let _ = writeln!(out, "    # TODO: unsupported assertion type: {other}");
638        }
639    }
640}
641
642/// Convert a module path (e.g., "html_to_markdown") to Ruby PascalCase module name
643/// (e.g., "HtmlToMarkdown").
644fn ruby_module_name(module_path: &str) -> String {
645    use heck::ToUpperCamelCase;
646    module_path.to_upper_camel_case()
647}
648
649/// Convert a `serde_json::Value` to a Ruby literal string, preferring single quotes.
650fn json_to_ruby(value: &serde_json::Value) -> String {
651    match value {
652        serde_json::Value::String(s) => ruby_string_literal(s),
653        serde_json::Value::Bool(true) => "true".to_string(),
654        serde_json::Value::Bool(false) => "false".to_string(),
655        serde_json::Value::Number(n) => n.to_string(),
656        serde_json::Value::Null => "nil".to_string(),
657        serde_json::Value::Array(arr) => {
658            let items: Vec<String> = arr.iter().map(json_to_ruby).collect();
659            format!("[{}]", items.join(", "))
660        }
661        serde_json::Value::Object(map) => {
662            let items: Vec<String> = map
663                .iter()
664                .map(|(k, v)| format!("{} => {}", ruby_string_literal(k), json_to_ruby(v)))
665                .collect();
666            format!("{{ {} }}", items.join(", "))
667        }
668    }
669}