刚刚学习 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 中,前一个示例和后一个示例有什么区别?
我也在寻找关于何时使用一个而不是另一个的规则
另一个相同但相反结果的示例,其中此代码有效:
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