在学习rspec语法时,我注意到这段代码是有效的:
context "given a bad list of players" do
let(:bad_players) { {} }
it "fails to create given a bad player list" do
expect{ Team.new("Random", bad_players) }.to raise_error
end
end
但这段代码没有:
context "given a bad list of players" do
let(:bad_players) { {} }
it "fails to create given a bad player list" do
expect( Team.new("Random", bad_players) ).to raise_error
end
end
这给了我一个错误:
Team given a bad list of players fails to create given a bad player list
Failure/Error: expect( Team.new("Random", bad_players) ).to raise_error
Exception:
Exception
# ./lib/team.rb:6:in `initialize'
# ./spec/team_spec.rb:23:in `new'
# ./spec/team_spec.rb:23:in `block (3 levels) in <top (required)>'
我的问题是:
- 为什么会这样?
- 在ruby中,前一个例子和后一个例子有什么不同?
我也在寻找rules个关于何时使用一个而不是另一个
还有一个相同但相反的结果示例,其中代码起作用:
it "has a list of players" do
expect(Team.new("Random").players).to be_kind_of Array
end
但是这个代码失败了
it "has a list of players" do
expect{ Team.new("Random").players }.to be_kind_of Array
end
在这种情况下,我得到的错误是:
Failure/Error: expect{ Team.new("Random").players }.to be_kind_of Array
expected #<Proc:0x007fbbbab29580@/Users/amiterandole/Documents/current/ruby_sandbox/tdd-ruby/spec/team_spec.rb:9> to be a kind of Array
# ./spec/team_spec.rb:9:in `block (2 levels) in <top (required)>'
我正在测试的类如下所示:
class Team
attr_reader :name, :players
def initialize(name, players = [])
raise Exception unless players.is_a? Array
@name = name
@players = players
end
end