【问题标题】:How to chain allow_any_instance_of with Rspec如何使用 Rspec 链接 allow_any_instance_of
【发布时间】:2023-03-17 11:04:02
【问题描述】:

我在学习 rspec 存根如何工作时遇到了一些麻烦。

我必须测试以下我希望将输出字符串测试为 html 的辅助方法:

def build_links(resource)
  YAML.load_file("config/admin_links.yml")[resource].collect do |link|
  active = (eval(link.last) == request.path) ? "active" : ""
  path = link.last.empty? ? "#" : eval(link.last)

  content_tag(:li, link_to(link.first, path), class: active)
end.join.html_safe

我想测试该方法是否以正确的方式构建链接。我不知道如何为 YAML.load_file("config/admin_links.yml")[resource] 做存根,以输出一个哈希,以便收集方法工作。

我已经使用

进行了测试
hash_link = {"Dashboard"=>"admin_dashboard_path", "Configurações"=>""}
allow_any_instance_of(YAML).to receive(:load_file).with(["test"]).and_return(hash_link)

u = YAML
allow(u).to receive_message_chain(:load_file, :[] ,:collect)

但到目前为止还没有成功。我应该如何进行模拟,所以 "YAML.load_file("config/admin_links.yml")[resource]" 返回 "{"Dashboard"=>"admin_dashboard_path", "Configurações"=>""" 所以方法collect 可以对变量起作用吗?

tnx,

【问题讨论】:

    标签: ruby-on-rails ruby testing rspec mocking


    【解决方案1】:

    load_fileYAML的类方法,不是实例方法,所以你可以用allow(YAML).to receive(:load_file).and_return(hash_link)存根它。

    【讨论】:

    • '它“测试”确实允许(YAML)接收(:load_file)。and_return(hash_link)allow_any_instance_of(ActionDispatch::Request)。接收(:路径).and_return(“/admin /Dashboard") build_links("test") end' 它失败并给出以下 Rspec 错误:Failure/Error: build_links("test") NoMethodError: undefined method `collect' for nil:NilClass
    • 我猜它没有传播收集方法的存根。但我不知道如何解决它。
    • 听起来哈希不包含您要查找的密钥。将[key] 更改为fetch(key) 以获得更有用的失败消息。
    • 另外,存根 ActionDispatch::Request 应该不是必需的,但也许这是以后的讨论。
    【解决方案2】:

    Rspec 经常会教你分区方法以便于存根。在这种情况下,提取 YAML 文件的读取,您可以非常简单地对结果进行存根。

    class MyClass
      def self.admin_links
        YAML.load_file("config/admin_links.yml")
      end
    
      def build_links(resource)
        self.class.admin_links[resource].collect do |link|
           # ...
        end
      end
    end
    
    allow(MyClass).to receive_message(:admin_links).and_return(hash_link)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2022-01-02
    相关资源
    最近更新 更多