如何用rspec测试flash组件



我的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测试来测试它

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

相关内容

  • 没有找到相关文章

最新更新