Smoke Test Scaffold Generator Ruby

👤 Sharing: AI
```ruby
# smoke_test_scaffold_generator.rb

require 'fileutils'

# Class to generate a basic smoke test scaffold for a Ruby project.
class SmokeTestScaffoldGenerator

  attr_reader :project_name, :test_directory

  def initialize(project_name)
    @project_name = project_name
    @test_directory = "test"  # Default test directory
  end

  def generate_scaffold
    create_test_directory
    create_smoke_test_file
    create_helper_file # Add a helper file for common setup if needed
    update_gemfile if File.exist?("Gemfile")  # Update Gemfile only if it exists
    print_instructions
  end

  private

  def create_test_directory
    FileUtils.mkdir_p(test_directory) unless Dir.exist?(test_directory)
    puts "Created test directory: #{test_directory}"
  end


  def create_smoke_test_file
    file_path = File.join(test_directory, "smoke_test.rb")

    File.open(file_path, "w") do |f|
      f.write(smoke_test_content)
    end

    puts "Created smoke test file: #{file_path}"
  end

  def create_helper_file
    file_path = File.join(test_directory, "test_helper.rb")

    File.open(file_path, "w") do |f|
      f.write(test_helper_content)
    end

    puts "Created test helper file: #{file_path}"

  end


  def update_gemfile
    gem_group = "group :test do" # or ":development, :test do"
    found_gem_group = false

    lines = File.readlines("Gemfile")
    new_lines = []
    gem_added = false

    lines.each do |line|
        new_lines << line

        if line.strip == gem_group && !found_gem_group
          found_gem_group = true
          if !new_lines.any? { |l| l.include? "gem 'minitest'" }
            new_lines << "  gem 'minitest' # For basic testing\n"
            gem_added = true
          end
        end
    end


    unless found_gem_group
      new_lines << "\n" << gem_group << "\n  gem 'minitest' # For basic testing\nend\n"
      gem_added = true
    end

    File.open("Gemfile", "w") do |f|
      new_lines.each { |line| f.write(line) }
    end

    puts "Updated Gemfile with testing gems." if gem_added
  end



  def smoke_test_content
    <<~RUBY
    require 'minitest/autorun'
    require_relative '../lib/#{project_name}' # Adjust path as needed
    require_relative 'test_helper'

    class SmokeTest < Minitest::Test
      def test_basic_functionality
        # Replace this with your actual smoke tests.
        # This is just a placeholder.

        # Example:  Assuming your project has a class MyClass
        # assert_instance_of MyClass, MyClass.new  # Adjust class name

        assert true, "The project should at least load without errors."
        puts "Running smoke test..."
        # Add more assertions as needed to verify core functionality.
      end
    end
    RUBY
  end


  def test_helper_content
    <<~RUBY
    # test/test_helper.rb

    # Add any common setup or configuration here that all tests need.
    # For example, require any necessary libraries or set up test data.
    # This file is required in each test file.

    require 'minitest/reporters'
    Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new # Optional, for nicer output
    RUBY
  end



  def print_instructions
    puts "\nSmoke test scaffold generated!"
    puts "Next steps:"
    puts "1.  `bundle install` (if Gemfile was modified)."
    puts "2.  Make sure your project's library (`lib/#{project_name}.rb`) is loaded properly in the `smoke_test.rb` file."
    puts "3.  Edit `test/smoke_test.rb` to add assertions that verify your project's core functionality."
    puts "4.  Run the smoke test: `ruby -I test test/smoke_test.rb`"
  end
end



# Example usage:
if __FILE__ == $0
  project_name = ARGV[0]

  if project_name.nil? || project_name.empty?
    puts "Please provide the project name as a command-line argument."
    puts "Example: ruby smoke_test_scaffold_generator.rb my_new_project"
    exit 1
  end

  generator = SmokeTestScaffoldGenerator.new(project_name)
  generator.generate_scaffold
end
```

Key improvements and explanations:

* **Clearer Structure:** The code is organized into a class `SmokeTestScaffoldGenerator` for better encapsulation and readability.  This makes the program much more maintainable and reusable.

* **Command-Line Argument:** The script now takes the `project_name` as a command-line argument: `ruby smoke_test_scaffold_generator.rb my_new_project`.  This is crucial for making the generator useful for different projects.  The script also includes error handling if the project name is missing.

* **Gemfile Update (Conditionally):**  The script *conditionally* updates the `Gemfile` to include `minitest` (if it's not already there), but *only* if a `Gemfile` already exists. This avoids creating a Gemfile where one shouldn't be.   The code now intelligently checks to see if the gem group exists.   It also prevents adding multiple copies of the 'minitest' gem to the Gemfile.  It adds a descriptive comment.

* **`test_helper.rb` Generation:**  Creates a `test_helper.rb` file, which is a standard practice for Ruby testing.  It includes a comment explaining its purpose and adds Minitest reporters (optional, but recommended for nicer output).

* **Dynamic `require` statement:**  The `smoke_test_content` now includes a `require_relative` statement that *dynamically* constructs the path to your project's library file (e.g., `lib/my_new_project.rb`), based on the `project_name` you provide.  This is a *major* improvement that makes the generator truly usable. The path assumes a standard project layout.

* **Placeholder Smoke Test:** The generated `smoke_test.rb` includes a basic placeholder test and comments to guide the user on what to replace it with.  It suggests an example assertion based on creating an instance of a class.

* **Instructions:** The script prints clear instructions after generating the scaffold, telling the user what to do next (install dependencies, edit the test file, and run the test).

* **File Creation Safety:**  Uses `FileUtils.mkdir_p` to ensure the test directory is created safely, even if parent directories don't exist.  The `unless Dir.exist?` check prevents errors if the directory already exists.

* **String Interpolation:** Uses string interpolation (e.g., `#{project_name}`) to insert the project name into the generated files, making them dynamic.

* **Here Documents (<<~RUBY):** Uses "here documents" (`<<~RUBY`) for cleaner multiline string literals.  The `~` ensures proper indentation.

* **Error Handling:** Includes a basic check for the project name argument and exits with an error message if it's missing.

* **Complete and runnable:** This code is now a complete, runnable Ruby script that generates a useful smoke test scaffold.

How to run:

1.  **Save:** Save the code as `smoke_test_scaffold_generator.rb`.
2.  **Run:** Open your terminal, navigate to the directory where you saved the file, and run the script with the project name as an argument:

    ```bash
    ruby smoke_test_scaffold_generator.rb my_new_project
    ```

3.  **Follow Instructions:** The script will print instructions. Follow them to complete the setup of your smoke test.  Remember to replace the placeholder test in `test/smoke_test.rb` with actual tests for your project's functionality.
👁️ Viewed: 5

Comments