gpt4 book ai didi

ruby-on-rails - 当我想测试我的助手类时,无法在 ActionView::TestCase 中使用 flash

转载 作者:太空宇宙 更新时间:2023-11-03 16:59:32 25 4
gpt4 key购买 nike

我想在我的助手类中测试一个方法,但是当我做类似的事情时:

require 'test_helper'

class ApplicationHelperTest < ActionView::TestCase
def test_flash_messages
flash[:notice] = "Hello World"
assert_equal "<div class=\"message-notice\">Hello World<\/div>", flash_messages
end
end

比我得到“NoMethodError: undefined method `flash' for nil:NilClass”

但是当我做类似的事情时:

flash = {}
flash[:notice] = "Hello World"
assert_equal "<div class=\"message-notify\">Hello World<\/div>", flash_messages

我收到相同的错误消息,但它在“application_helper.rb:6:in `flash_messages'”中调用

顺便说一句,我的 application_helper 看起来像:

module ApplicationHelper

def flash_messages
fl = ''
flash.each do |key,msg|
if flash[key]
fl = fl + "<div class=\"message-#{key}\">#{msg}</div>"
end
flash[key] = nil
end
return fl
end

end

这在网站上有效,但我希望能够通过单元测试来测试这种方法。

最佳答案

只需定义一个 flash 方法作为测试中的 stub :

class ApplicationHelperTest < ActionView::TestCase
def flash
@flash ||= {}
end

def test_flash_messages
flash[:notice] = "Hello World"
assert_equal "<div class=\"message-notice\">Hello World<\/div>", flash_messages
end
end

关于ruby-on-rails - 当我想测试我的助手类时,无法在 ActionView::TestCase 中使用 flash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4031209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com