rspec“描述”方法(和其他)的源代码?

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

我现在正在浏览 Michael Hartl 的 Rails 教程,发现我不断被鼓励使用奇妙的方法,这些方法可以莫名其妙地做出令人惊奇的事情。他总体上能胜任地解释他们的工作,但没有真正解释他们为什么以及如何工作。

具体来说,我刚刚在 github 上掠夺了 rspec gem,搜索“describe”方法的源代码。我找不到它。现在已经阅读了大量的源代码(理解率约为25%)来寻找它,我知道一旦找到,我将需要查看它的父类和模块来了解一定量的继承,然后再进行操作。能真正抓住(然后再不放开)“描述”的骨肉。

我不介意努力掌握这个概念,我喜欢在完全理解新语言之前尝试阅读代码,这样我就可以稍后再次阅读它,并使用我的理解力的比较来衡量我的水平流畅度。我只想要一个踢球者。描述或文件位置,也许还有一些帮助提示可以帮助我开始。

例如...

我发现了这个:

  #     RSpec.describe "something" do # << This describe method is defined in
  #                                   # << RSpec::Core::DSL, included in the
  #                                   # << global namespace (optional)

和 rpsec/core/dsl 状态:

# DSL defines methods to group examples, most notably `describe`,
# and exposes them as class methods of {RSpec}. They can also be
# exposed globally (on `main` and instances of `Module`) through
# the {Configuration} option `expose_dsl_globally`.

但是该文件中没有“类描述”或def“描述”之类的内容。

SO:谁能告诉我“描述”方法在哪里,它到底是如何工作的,或者(如果不是的话)为什么我天真地在错误的位置寻找错误的东西?

ruby-on-rails rspec rubygems dsl
2个回答
3
投票

如您所知,

describe
context
方法之间没有区别,您可以互换使用它们。 Rspec 开发人员不能让自己对不同的方法名称重复相同的代码,因此他们将声明移至

module RSpec
  module Core
    class ExampleGroup
      def self.define_example_group_method(name, metadata={})
        # here they really define a method with given name using ruby metaprogramming
        define_singleton_method(name) do |*args, &example_group_block|

稍后为所有相同功能的 DSL 方法调用该方法:

define_example_group_method :example_group
define_example_group_method :describe
define_example_group_method :context

因此,如果您正在寻找

describe
方法源,请深入研究
define_example_group_method
,并假设
name
参数等于
describe
并且
example_group_block
是您的块体。


0
投票

RSpec 代码库并不是一件容易让您头脑清醒的小事。但是,这些链接应该可以帮助您开始...

这一行定义了describe关键字:

https://github.com/rspec/rspec-core/blob/master/lib/rspec/core/example_group.rb#L246

该行上方的方法可以为您完成繁重的工作。花点时间阅读它。

这部分然后公开生成的方法:

https://github.com/rspec/rspec-core/blob/master/lib/rspec/core/dsl.rb#L54

祝你好运!

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