2011-08-27 67 views
0

假設我有一個user_spec.rb文件,並且我在這個文件中有一些測試。如何在單個spec文件中正確添加上下文或單元測試的單獨測試?

如何添加或分組相關的測試?

我想我讀了我可以添加上下文,但我不知道這是我之後。

我想要做這樣的事情:

describe User do 

    password tests do 
    length related tests do 
     it "..." do 
     end 
     it "..." do 
     end 
    end 

    bad characters related tests do 
     it "..." do 
     end 
     it "..." do 
     end 
    end 
    end 

end 

什麼是這樣做,如果有可能的正確方法?

回答

2

我覺得context僅僅是decribe一個別名,所以你應該能夠做到這一點:

describe User do 
    describe "password" do 
    describe "length" do 
     it "must be shorter than 400 characters" do 
     end 
     it "must be longer than 3 character" do 
     end 
    end 

    describe "characters" do 
     it "newline is not allowed" do 
     end 
    end 
    end 
end 
+0

在每個子描述塊中,我可以爲該範圍設置變量嗎?但這些變量不應在任何其他描述塊中提供。 – Blankman

2

可以使用嵌套的描述塊組相關測試

describe User do 

    describe "password tests" do 
    describe "length related tests" do 
     it "..." do 
     end 
     it "..." do 
     end 
    end 

    describe "bad characters related tests" do 
     it "..." do 
     end 
     it "..." do 
     end 
    end 
    end 

end 

編輯:回答你的問題:「在每個子描述塊中,我可以爲該範圍設置變量嗎?但這些變量不應該在任何其他描述塊中可用」:在每個描述塊中,創建一個新範圍,這意味着這可以起作用:

describe "password tests" do 
    where_i_am = "inside password tests" 
    describe "length related tests" do 
     #some code 
     puts where_i_am #outputs "inside password tests" 
    end 
end 

puts where_i_am #undefined local variable or method ...