2013-11-15 71 views
1

我正在運行兩個測試,其中一個失敗,一個通過。唯一的區別是使用:should vs :expect。爲什麼一個測試工作,另一個不工作?Rspec:應該vs:期望與正則表達式

通過的測試:

it "returns no comma, when the integer is smaller than 1000" do 
    separate_comma(random_num(0, 999)).should match /^\d{1,3}$/ 
end 

失敗的測試:

it "explanation" do 
    expect(separate_comma(random_num(0, 999))).to match /^\d{1,3}$/ 
end 

這裏的無聊的東西:

def random_num(min, max) 
    rand(max - min + 1) + min 
end 

def separate_comma(number, delimiter = ',') 
    new = number.to_s.reverse.scan(/.../).join(delimiter) 
end 
+3

如果正則表達式在parens中,它工作嗎?測試的輸出是什麼? –

+0

太棒了。那樣做了,謝謝! –

回答

3

這不是一個答案,但一個相關的問題。以下規範通過了從OP代碼複製的基本內容。有人可以解釋爲什麼OP的規範在expect的情況下會失敗,爲什麼圍繞正則表達式的括號會有所作爲? (注意:我正在使用Ruby 2.0和RSpec 2.14)

def random_num(min, max) 
    rand(max - min + 1) + min 
end 

def separate_comma(number, deliminator = ',') 
    new = number.to_s.reverse.scan(/.../).join(deliminator) 
end 

describe "rspec expectations involving match, regex and no parentheses" do 

    it "works for should" do 
    separate_comma(random_num(0, 999)).should match /^\d{1,3}$/ 
    end 

    it "works for expect" do 
    expect(separate_comma(random_num(0, 999))).to match /^\d{1,3}$/ 
    end 

end