学习如何使用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"