【问题标题】:Using expect matcher in Rspec在 Rspec 中使用期望匹配器
【发布时间】:2013-08-22 00:59:38
【问题描述】:

我很确定这是一个非常愚蠢的问题,但我是 Cucumber、Ruby 和 Rspec 的新手,我正在努力解决一些非常基本的问题。

我安装了 rspec gem,我想使用期望匹配器: 期望(实际).to eq(预期)

似乎我应该能够简单地要求 rspec/expectations 然后执行这些命令,但是它不起作用。

我错过了什么?

1.9.3-p448 :001 > require 'rspec'
 => true 
1.9.3-p448 :002 > require 'rspec/expectations'
 => true 
1.9.3-p448 :003 > expected = "this"
 => "this" 
1.9.3-p448 :004 > actual = "this"
 => "this" 
1.9.3-p448 :005 > expect(actual).to eq(expected)
NoMethodError: undefined method `expect' for main:Object
from (irb):5
from /Users/lpc/.rvm/rubies/ruby-1.9.3-p448/bin/irb:16:in `<main>'

奇怪的是“应该”可以正常工作。

1.9.3-p448 :006 > expected.should == actual
 => true 

感谢您的帮助。

【问题讨论】:

    标签: rspec


    【解决方案1】:

    如果使用 Cucumber,您只需在 env.rb 文件中包含“rspec/expectations”,然后在步骤定义中使用预期的语法。

    env.rb:

     require 'rspec/expectations'
    

    steps.rb:

     Then(/^I should be able to use rspec$/) do
       expected = "this"
       actual= "this"
       expect(actual).to eql(expected)
     end
    

    我的错误是在 ruby​​ 控制台中错误地测试了这个语法。你不能这样做,因为 Cucumber 为你做了一些自动的东西。

    “当 cucumber 看到定义了 Spec::Matchers 和 Spec::Expectations 模块时,它会隐式地将它们包含在执行步骤的 World 中。”

    【讨论】:

      【解决方案2】:

      我真的很想在 Rails 控制台中试验 expect() 匹配器。我意识到我可以将它们包装在一个 describe/it 块中,但我在控制台中没有得到有用的结果。

      describe "basic rspec feasure" do it "should do my bidding" do expect(:a).to eq(:a) end; end
      返回RSpec::Core::ExampleGroup::Nested_2

      有没有人了解一个人如何能够做到这一点?我很好奇在 rspec 内部发送通过/失败条件的路径是什么。我意识到这是 rspec 的非典型和高级用法,但我很好奇 ;)

      【讨论】:

      • test = describe "basic rspec feasure" do it "should do my bidding" do expect(:a).to eq(:a) end; end test.run 如果测试通过则为真
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多