RSpec测试/输出中的可读性

时间:2016-07-20 22:12:09

标签: rspec readability

我使用RSpec相当新。我想知道关于测试/输出可读性的最佳实践是什么。测试类方法的Here I have two examples。第一个是直接(?)可读测试,但输出有点模棱两可。第二个在读取时有详细/冗余测试,但输出非常清晰。

class StringTester
  def self.is_hello?(s)
    s == 'hello'
  end
end

RSpec.describe StringTester do
  # Tests are fairly readable in English...
  describe '::is_hello?' do
    it { expect(StringTester.is_hello?('hello')).to be_truthy }
    it { expect(StringTester.is_hello?('something else')).to be_falsey }
  end
end

# ...but the output is ambiguous without going back to look at the tests.
# Output:
# StringTester
#   ::is_hello?
#     should be truthy
#     should be falsey


RSpec.describe StringTester do
  # Tests are redundant when read in English...
  describe '::is_hello?' do
    it 'is true for "hello"' do
      expect(StringTester.is_hello?('hello')).to be_truthy
    end
    it 'is false for "something else"' do
      expect(StringTester.is_hello?('something else')).to be_falsey
    end
  end
end

# ...but the output is very straightfoward.
# Output:
# StringTester
#   ::is_hello?
#     is true for "hello"
#     is false for "something else"

那么一种方式被认为是比另一方更好的做法吗?

1 个答案:

答案 0 :(得分:1)

我想说第二种形式通常更可取,因为it描述允许您解释正在测试的规则。在上面的代码中,它看起来只是重复,因为这是一个非常简单,人为的例子。

假设您正在测试检查输入是否为正的代码:

describe '#positive?' do it 'is true for numbers greater than zero' do expects(Foo.positive?(1)).to be_truthy end it 'is false for numbers less than zero' do expects(Foo.positive(-1)).to be_falsey end end

然后RSpec输出变得更具可读性,因为它描述的是整体行为,而不仅仅是单个示例的输出。