7

学习如何 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)>'
4

1 回答 1

9

您应该对这些测试使用普通括号:

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"
于 2014-09-30T10:04:51.490 回答