如何使用 rspec 测试 Flash 组件

How to test flash component with rspec

我的 rails 应用程序中有以下视图组件

class Elements::FlashComponent < ViewComponent::Base
  def initialize(*)
    super
  end

  def flash_class(level)
    case level
    when "notice"
      "alert alert-info"
    when "success"
      "alert alert-success"
    when "error"
      "alert alert-danger"
    when "alert"
      "alert alert-warning"
    end
  end
end

我想用 rspec test

来测试它
require "rails_helper"

RSpec.describe Elements::FlashComponent, type: :component do
  it "renders flash notification" do
    with_controller_class Customer::DashboardController do
      flash.now[:notice] = "Notification message!"
      render_inline described_class.new()
    end

    expect(rendered_component).to have_text "Notification message!"
    expect(rendered_component).to have_selector "label"
    expect(rendered_component).not_to have_selector "img"
  end
end

但每次我 运行 测试时,我都会看到以下消息

NameError: undefined local variable or method `flash' for #<RSpec::ExampleGroups::ElementsFlashComponent "renders flash notification"

如何解决?

最后,我修复了它,在 flash 之前添加了 controller.

    with_controller_class Customer::DashboardController do
      controller.flash[:notice] = "Notification message!"
      render_inline described_class.new()
    end