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

标签 ruby tdd rspec2

刚刚学习 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/

相关文章:

ruby - 完成所有测试后,应使用什么 RSpec 钩子(Hook)来执行清理任务?

html - 如何在 Ruby on Rails 5 中使用起始值自动增加自定义 ID?

tdd - 如何使用 NSpec 在 Visual Studio 中进行调试

ruby-on-rails - 如何撤消在我的 Rails/RSpec 测试中所做的文件系统更改?

ruby - 使用 Rspec codeschool 3 级挑战 5 进行测试

testing - 我为什么要实践测试驱动开发,我应该如何开始?

hash - 尝试模拟哈希元素的获取和放置时,RSpec 无法定义单例错误

ruby-on-rails - 分页问题 (will_paginate)

ruby-on-rails - Ruby on Rails的奇怪事件

ruby-on-rails - 以面向对象的方式对 Rails 中的关联进行 nil 检查