RSpec测试循环输出

时间:2016-03-24 22:30:27

标签: ruby rspec

我想测试以下方法的输出:

def print_books
  @books.each do |book|
    puts "#{book.id}. #{book.name}"
  end
end

我的RSpec代码如下:

before(:all) do 
 @library = Library.new
end

it "prints the correct names with ascendant ids" do 
  expect(STDOUT).to receive(:puts).with("4. Harry Potter","8. Lord of the Rings")
  @library.print_books
end

问题是只打印了第一本书,因为我认为只考虑了第一本书。

1 个答案:

答案 0 :(得分:1)

当您编写with(a, b)时,您告诉RSpec您希望使用参数a, b将该方法称为一次。例如,这将通过:

it 'prints' do
  expect(STDOUT).to receive(:puts).with(1, 2)
  puts 1, 2
end

你正在尝试做一些不同的事情;您希望使用puts调用book_a,然后使用book_b再次调用 。您可以使用ordered将其指定为RSpec。

it 'prints each book' do
  expect(STDOUT).to receive(:puts).with('1. Harry Potter').ordered
  expect(STDOUT).to receive(:puts).with('8. Lord of the Rings').ordered
  @library.print_books
end

RSpec现在将检查puts是先使用"1. Harry Potter",然后使用"8. Lord of the Rings"。如果缺少一本书,则会出现第三本书,或者拨打错误的订单,测试将失败。

相关问题