ruby – Rspec 3 vs Rspec 2匹配器

学习如何使用Rspec 3.我对匹配器有疑问.我关注的教程基于Rspec 2.

describe Team do

  it "has a name" do
    #Team.new("Random name").should respond_to :name
    expect { Team.new("Random name") }.to be(:name)
  end


  it "has a list of players" do
    #Team.new("Random name").players.should be_kind_of Array
    expect { Team.new("Random name").players }.to be_kind_of(Array)
  end

end

为什么代码导致错误,而我注释掉了通过折旧警告.

错误

Failures:

  1) Team has a name
     Failure/Error: expect { Team.new("Random name") }.to be(:name)
       You must pass an argument rather than a block to use the provided matcher (equal :name),or the matcher must implement `supports_block_expectations?`.
     # ./spec/team_spec.rb:7:in `block (2 levels) in <top (required)>'

  2) Team has a list of players
     Failure/Error: expect { Team.new("Random name").players }.to be_kind_of(Array)
       You must pass an argument rather than a block to use the provided matcher (be a kind of Array),or the matcher must implement `supports_block_expectations?`.
     # ./spec/team_spec.rb:13:in `block (2 levels) in <top (required)>'

解决方法

您应该使用常规括号进行这些测试:

expect(Team.new("Random name")).to eq :name

使用大括号时,您传递的是一段代码.对于rspec3,这意味着您将对此块的执行而不是执行结果抱有一些期望,例如

expect { raise 'hello' }.to raise_error

编辑:

但请注意,此测试将失败,因为Team.new返回一个对象而不是符号.您可以修改测试,以便通过:

expect(Team.new("Random name")).to respond_to :name

# or

expect(Team.new("Random name").name).to eq "Random name"

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...