爲了向更多TDD/BDD開發模式邁進,我正在齊心協力圍繞Rspec進行研究。然而,我還有很長一段路要走,並且在一些基本面上掙扎:何時以及何時不存根/模擬測試
就像我應該在什麼時候使用模擬/存根,什麼時候不應該?舉例來說,這種情況下:我有一個Site
模型has_many :blogs
和Blog
模型has_many :articles
。在我的Site
模型中,我有一個回調過濾器,爲每個新網站創建一組默認的博客和文章。我想測試該代碼,所以這裏有:
describe Site, "when created" do
include SiteSpecHelper
before(:each) do
@site = Site.create valid_site_attributes
end
it "should have 2 blogs" do
@site.should have(2).blogs
end
it "should have 1 main blog article" do
@site.blogs.find_by_slug("main").should have(1).articles
end
it "should have 2 secondary blog articles" do
@site.blogs.find_by_slug("secondary").should have(2).articles
end
end
現在,如果我運行該測試,一切都會通過。然而,它也很慢,因爲它會創建一個新網站,兩個新博客和三個新文章 - 每一個測試!所以我想知道,這是使用存根的好候選者嗎?讓我們一起去吧:
describe Site, "when created" do
include SiteSpecHelper
before(:each) do
site = Site.new
@blog = Blog.new
@article = Article.new
Site.stub!(:create).and_return(site)
Blog.stub!(:create).and_return(@blog)
Article.stub!(:create).and_return(@article)
@site = Site.create valid_site_attributes
end
it "should have 2 blogs" do
@site.stub!(:blogs).and_return([@blog, @blog])
@site.should have(2).blogs
end
it "should have 1 main blog article" do
@blog.stub!(:articles).and_return([@article])
@site.stub_chain(:blogs, :find_by_slug).with("main").and_return(@blog)
@site.blogs.find_by_slug("main").should have(1).articles
end
it "should have 2 secondary blog articles" do
@blog.stub!(:articles).and_return([@article, @article])
@site.stub_chain(:blogs, :find_by_slug).with("secondary").and_return(@blog)
@site.blogs.find_by_slug("secondary").should have(2).articles
end
end
現在所有的測試仍然通過,事情也有點快。但是,我的測試時間增加了一倍,整個練習讓我覺得完全毫無意義,因爲我不再測試我的代碼,我只是測試我的測試。現在
,或者我已經完全錯過了嘲笑/存根的點,或者我接近它根本上就是錯誤的,但我希望有人也許能夠之一:
- 提高我上面的測試所以它以實際測試我的代碼的方式使用存根或模擬,而不是我的測試。
- 或者,告訴我是否應該在這裏使用存根 - 或者實際上這是完全不必要的,我應該將這些模型寫入測試數據庫。
謝謝,這是一個有用的迴應。:) – aaronrussell 2010-09-14 12:41:36