2012-03-29 25 views
1

我有一個測試我試圖調試,我注意到值沒有被正確設置爲用戶屬性。當我從調試控制檯運行p user.height_feetp user.height_inches時,我得到了nil,相反,我期望它們在第一次迭代中分別返回18。然而,p invalid_height.firstp invalid_height.second正確返回18RSpec - 值沒有正確設置爲用戶屬性

下面是代碼:

describe "when height is invalid" do 
    invalid_height = [[1, 8], [8, 2], [5, 13], ['text', 'text'], ['text', 11], [5, 'text'], ['', '']] 
    invalid_height.each do |invalid_height| 
    before do 
     user.height_feet = invalid_height.first 
     user.height_inches = invalid_height.second 
    end 

    it "should not be valid" do 
     debugger 
     user.should_not be_valid 
    end 
    end 
end 

,並在調試終端輸出:

(rdb:1) p user.height_feet 
nil 
(rdb:1) p user.height_inches 
nil 
(rdb:1) p invalid_height.first 
1 
(rdb:1) p invalid_height.second 
8 

有人在#rubyonrails IRC頻道建議,它可能是一個範圍的問題,問我用戶被定義,說我的beforeit塊可能指的是不同的用戶。我不認爲這應該是一個問題,因爲我在同一個spec文件中有beforeit塊的其他測試運行得很好。思考?

回答

2

你需要考慮你的代碼在做什麼。

它穿過每創建一個beforeit "should not be valid" 但這些都是EVAL-ED在同一範圍內。

因此,您創建的before

before do 
    user.height_feet = 1 
    user.height_inches = 8 
end 

before do 
    user.height_feet = 8 
    user.height_inches = 2 
end 

... 

before do 
    user.height_feet = "" 
    user.height_inches = "" 
end 

負載而創建的it

it "should not be valid" do 
    debugger 
    user.should_not be_valid 
end 

it "should not be valid" do 
    debugger 
    user.should_not be_valid 
end 

... 

it "should not be valid" do 
    debugger 
    user.should_not be_valid 
end 

負載所以所有的測試的結果基本上是

before do 
    user.height_feet = "" 
    user.height_inches = "" 
end 

it "should not be valid" do 
    debugger 
    user.should_not be_valid 
end 

我認爲這不是你的意圖。

明顯的解決方法是使用context塊。這將把每一對語句都封裝在一個上下文中。

[[1, 8], [8, 2], [5, 13], ['text', 'text'], ['text', 11], [5, 'text'], ['', ''] 
].each do |feet, inches| 
    context "with an invalid height of #{feet} feet, #{inches} inches" do 

    before do 
     user.height_feet = feet 
     user.height_inches = inches 
    end 

    it "should not be valid" do 
     debugger 
     user.should_not be_valid 
    end 
    end 
end 
+1

謝謝!非常豐富。我不熟悉'context'塊,因爲我是ruby的新手,但我會研究它來學習更多。 – Nick 2012-03-29 03:48:47

相關問題