RSpec测试模块

时间:2013-01-09 23:07:25

标签: ruby rspec

我是RSpec和TDD的新手。我想知道是否有人可以帮我创建一个非常适合这个模块的测试:

module Kernel
  # define new 'puts' which which appends "This will be appended!" to all puts output 
  def puts_with_append *args
    puts_without_append args.map{|a| a + "This will be appended!"}
  end

  # back up name of old puts
  alias_method :puts_without_append, :puts

  # now set our version as new puts
  alias_method :puts, :puts_with_append
end

我希望我的测试能够检查来自'puts'的内容是否以“这将被追加!”结束。这是一个充分的测试吗?我该怎么做?

1 个答案:

答案 0 :(得分:2)

最好的测试测试你想要实现的目标,而不是你如何实现它...将测试与实施相结合会使你的测试变得脆弱。

因此,使用此方法尝试实现的是在加载扩展时更改为“puts”。测试方法puts_with_append没有达到这个目标......如果你以后不小心将其重新别名为其他东西,那么你所希望的看跌期权将无效。

但是,在不使用实现细节的情况下进行测试会相当困难,因此我们可以尝试将实现细节推送到他们不会改变的地方,例如 STDOUT

仅测试内容

$stdout.stub!(:write)
$stdout.should_receive(:write).with("OneThis will be appended!")
puts "One"

完整测试

我会在第二天左右将其变成博客文章,但我认为您还应该考虑到您已经获得了一个和多个参数的预期结果,并且您的测试应该易于阅读。我使用的最终结构是:

要求“rspec” 要求“./your_extention.rb”

describe Kernel do
  describe "#puts (overridden)" do
    context "with one argument" do
      it "should append the appropriate string" do
        $stdout.stub!(:write)
        $stdout.should_receive(:write).with("OneThis will be appended!")
        puts "One"
      end
    end

    context "with more then one argument" do
      it "should append the appropriate string to every arg" do
        $stdout.stub!(:write)
        $stdout.should_receive(:write).with("OneThis will be appended!")
        $stdout.should_receive(:write).with("TwoThis will be appended!")
        puts("One", "Two")
      end
    end
  end
end