2016-07-20 98 views
0

我對使用RSpec相當陌生。我想知道關於測試/輸出可讀性的最佳實踐。測試類方法的Here I have two examples。第一個有直接的(?)可讀性測試,但輸出有點模糊。第二個在讀取時有詳細/冗餘測試,但輸出非常清晰。RSpec測試/輸出中的可讀性

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

沒有單一的最佳做法,所以任何答案都會是一個意見。 –

回答

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的輸出然後變得更具可讀性,因爲它描述的是整體行爲而不僅僅是輸出個人例子。