gpt4 book ai didi

ruby - Rspec : expect vs expect with block - what's the difference?

转载 作者:太空宇宙 更新时间:2023-11-03 16:42:26 24 4
gpt4 key购买 nike

刚刚学习 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)>'

我的问题是:

  1. 为什么会这样?
  2. 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

最佳答案

如前所述:

expect(4).to eq(4)

这是专门测试您作为参数发送给方法的值。当您在做同样的事情时尝试测试引发的错误时:

expect(raise "fail!").to raise_error

您的参数立即被评估,异常将被抛出,您的测试将在那里爆炸。

但是,当您使用 block 时(这是基本的 ruby​​), block 内容不会立即执行 - 它的执行取决于您调用的方法(在本例中,expect 方法处理何时执行你的 block ):

expect{raise "fail!"}.to raise_error

我们可以看一个可能处理这种行为的示例方法:

def expect(val=nil)
if block_given?
begin
yield
rescue
puts "Your block raised an error!"
end
else
puts "The value under test is #{val}"
end
end

你可以看到这里是 expect 方法手动挽救你的错误,以便它可以测试是否引发错误等。 yield 是一个 ruby 方法执行传递给该方法的任何 block 的方式。

关于ruby - Rspec : expect vs expect with block - what's the difference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42596436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com