使用 IRB 中的 RSpec

发布日期:2026-06-25 05:53:02   来源 : 杭州电子商务研究院    浏览量 :12
杭州电子商务研究院 发布日期:2026-06-25 05:53:02  
12

介绍

这是一个快速指南,向您展示使rspecirb上运行所需的必要步骤。

执行

让我们从加载 rspec 核心和期望开始。

      require 'rspec/core' # this is what really runs your tests
require 'rspec/expectations' # readable syntax for checking properties of your code
    

然后我们包括匹配器模块。

      include RSpec::Matchers # rspec will NOT automatically include this for you if you are using irb
    

现在我们可以测试一下我们的期望了:

      >> expect(1).to eq(1)
=> true
    

哇哦!你准备好了……不,试试这个。

      2.3.0 :003 > array_hashes = [{lol: nil}]
 => [{:lol=>nil}]
2.3.0 :005 > include RSpec::Matchers
 => Object
2.3.0 :006 > expect(array_hashes).to include(have_key(:lol))
    

您将遇到如下所示的错误:

      TypeError: wrong argument type RSpec::Matchers::BuiltIn::Has (expected Module)
        from (irb):6:in `include'
        from (irb):6
        from /usr/local/rvm/rubies/ruby-2.3.0/bin/irb:11:in `<main>'
    

如果你仔细阅读错误,它需要一个模块作为参数,这是因为当使用 irb 时,我们在主 ruby​​ 对象中运行。此对象有另一个名为include 的方法,该方法优先于 rspec 的include方法

为了解决这个问题,我们可以将 RSpec::Matcher添加到 main 的单例类中:

      $ irb
irb(main):001:0> require 'rspec/expectations'
=> true
irb(main):002:0> singleton_class.prepend RSpec::Matchers
=> #<Class:#<Object:0x007ff08a8d6620>>
irb(main):003:0> array_hashes = [{lol: nil}]
=> [{:lol=>nil}]
irb(main):004:0> expect(array_hashes).to include(have_key(:lol))
=> true
    

我们在AgileVentures进行群众会议时遇到了这个问题,并在我们得到这个黑客攻击的 rspec 期望 github 页面上提出了这个问题。

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据