2013-02-15 32 views
0

我想要那些已經測試的方法,但是我嘗試的所有方法似乎都不符合最佳實踐,也不能工作。需要其他方法返回(stubbing?)的Rspec測試實例方法

可能有人能用這個支持我嗎?

代碼進行測試

def any_subset_greater? 
    divisors_sums.any?{|sum| sum > @value} 
end 

def no_subset_equal? 
    !divisors_sums.any?{|sum| sum == @value} 
end 

def check_room 
    any_subset_greater? && no_subset_equal? 
end 

RSPEC TRY

第一指定似乎不爲除數的方法和實例變量@value設置適當的返回值。

describe "#any_subset_greater?" do 
    # Examples: 
    # [1,2] > 4 #=> false 
    # [1,2,3] > 4 #=> true 
    specify "returns true, when value in the array is greater" do 
    number.stub(:divisors){[1,2,3]} 
    number.stub(:value) {4} 
    expect(number.any_subset_greater?).to be_true 
    end 

end 

describe "#no_subset_equal?" do 
    # Examples: 
    # 4 === [1,2,4] #=> false 
    # 4 === [1,2,3] #=> false 
    # 4 === [1,2,6] #=> true 
end 

describe "#check_room" do 
    # testing condition from methods above 
end 
+1

這看起來像一個精緻的外殼,但什麼你嘗試的描述方法? – 2013-02-15 18:37:55

+1

'divisor_sums'從哪裏來?另外,你不應該爲被測對象使用'mock',因爲它不包含你的邏輯代碼。 – 2013-02-15 18:41:45

+0

@dave:是的......我想嘗試一下,但我所做的一切似乎都不太合適。當我用一個值殘缺除數時, 亞倫:我不知道怎麼......嘗試了幾件事......任何線索?你可以發表一個嘲笑這個例子嗎? – radosch 2013-02-15 18:58:46

回答

1

不知道你的對象是如何設置的,這個答案只是一個猜測。我會假設你的對象看起來像:

class SpecialNumber 
    attr_reader :divisor_sums 

    def initialize(n) 
    @value = n 
    # @divisor_sums is calculated here 
    end 

    # rest of your methods 
end 

所以用這個對象考慮,第一組測試可能看起來像:

subject(:special_number) { SpecialNumber.new 4 } 

describe "#any_subset_greater?" do 
    context "no divisor sums greater than value" do 
    it do 
     special_number.stub(:divisor_sums).and_return [1, 2] 

     expect(special_number.any_subset_greater?).to be_false 
    end 
    end 

    context "one divisor sum greater than value" do 
    it do 
     special_number.stub(:divisor_sums).and_return [1, 2, 5] 

     expect(special_number.any_subset_greater?).to be_true 
    end 
    end 

    context "several divisor sums greater than value" do 
    it do 
     special_number.stub(:divisor_sums).and_return [1, 2, 5, 6] 

     expect(special_number.any_subset_greater?).to be_true 
    end 
    end 
end 

但你不必存根這個。如果這是一個簡單的類,只需每次都創建一個新的對象,這已預期除數是可以接受的:

describe "#any_subset_greater?" do 
    context "no divisor sums greater than value" do 
    it do 
     expect(SpecialNumber.new(3).any_subset_greater?).to be_false 
    end 
    end 
end 
+0

嘿,非常感謝你! 是否有一個原因,爲什麼你使用describe> context>而不是describe>指定(帶註釋) 我發現,我把它存在錯誤的地方(facepalm)。 我只會在下面發佈適用於我的解決方案。 – radosch 2013-02-16 18:28:02

+0

「指定」是「it」的別名。對我來說,使用'context'可以提供語義。在一天結束時,這是個人喜好。 ESP。對於測試這個直截了當的。 – 2013-02-16 19:20:22