如何将Rspec的let类型记录下来?

问题描述 投票:0回答:1

假设我有以下代码

let(:document) { FactoryBot.create :document }
let(:mail) do
  # @type [User]
  celebrated_user = FactoryBot.create :user
  # @type [Rule]
  rule = FactoryBot.create :rule, document: document
  CelebrationMailer.birthday celebrated_user, document, rule
end

CelebrationMailer#birthday被记录如下

# @param [User] celebrated_user
# @param [Document] document
# @param [Rule] rule

let(:mail) RubyMine(可能还有其他一些带类型的工具)能够识别出 文件 变量类型为Object。

RubyMine's tooltip about wrong type

我怎样才能将 ,所以工具可以识别 文件 letvariable作为文档类型?

我试过 @type, @return, @attr_reader.

ruby rspec rubymine yard
1个回答
0
投票

那么,什么是 let 做什么?它创建了一个方法,其名称由符号参数给出,其返回值由块的返回值给出。

所以,如果你想为它写一个类型,你就必须写一个

  • 把这个符号变成一个方法名
  • 把块的返回类型变成方法的返回类型。

我很确定,用RDoc或YARD类型的符号是不可能的。

所以,你能做的最好的事情是一个简单的例子。合成属性阅读器:

# @!attribute [r] document
#   @return [Document] a fake document
let(:document) { FactoryBot.create :document }

注意到YARD 是否 支持 但宏显然只能访问源代码中的内容,而且块的返回类型是 源代码的一部分。事实上,你所展示的文档块看起来像是由一个看起来有点像这样的宏生成的。

# Defines a memoized method
# @param [Symbol] name the method name
# @param block how to compute the value
# @!macro [attach] let
#   @!attribute [r] $1
#     @return the value defined by the block
def let(name, &block) end

这将告诉YARD,无论它在哪里看到一个调用到 let的第一个参数的属性读取器插入一个合成文档块。let.

然而,它不会允许你使用块的类型。这些是唯一存在的插值变量。

  • $0 - 被调用的方法名称
  • $1, $2, $3, ... - 方法调用中的第N个参数。
  • $& - 全源线

ぐ或 工作,是如果 let 第二个参数是类型,那么你可以写一个像这样的宏。

# Defines a memoized method
# @param [Symbol] name the method name
# @param [Module] type the type of the memoized value
# @param block how to compute the value
# @!macro [attach] let
#   @!attribute [r] $1
#     @return [${-1}] the value defined by the block
def let(name, type, &block) end

然后你就可以像这样调用它

let(:document, Document) { FactoryBot.create :document }

但是,这不是RSpec的设计方式, 所以你能做的最好的就是我第一个建议中的合成属性读取器。

© www.soinside.com 2019 - 2024. All rights reserved.