2011-08-12 112 views
1

我希望能夠寫一個規範,如RSpec的報告VS性能

describe Foo do 
    before :each do 
     @hash = some_very_expensive_setup_op 
    end 
    describe "hash" do 
     subject{@hash} 
     its([:a]){should == 10} 
     its([:b]){should == 20} 
     its([:c]){should == 30} 
    end 
end 

和RSpec的工作方式,相當合理,是每個塊之前塊之前執行。在許多情況下,這是你想要的,但在上述情況下,在我的許多測試中,最後的葉塊斷言沒有副作用。

我可以重寫規範爲

describe Foo do 
    before :each do 
     @hash = some_very_expensive_setup_op 
    end 
    describe "hash" do 
     it "should have some attributes" do 
      @hash[:a].should == 10 
      @hash[:b].should == 20 
      @hash[:c].should == 30 
     end 
    end 
end 

現在所有的斷言單個塊內進行。該規範在功能上是相同的,但我沒有得到第一個版本的詳細報告,列出了文檔格式化程序中的每個斷言。

輸出對我來說很重要,因爲我嘗試將輸出用作Web api消費者的文檔。例如,對於我的規格之一,我有一個像

GET /status.json?ago=:ago 
    it should behave like authenticated 
    GET /status.json 
     accepts a valid user 
     rejects an invalid user 
    request 
    request attributes 
     :ago - number of seconds of history to calculate statistics 
     :current_user (implicit) 
    response attributes 
     scale 
     downtime 
     points 
     nextlevel 

輸出,但爲屬性的數量的增加它會減慢規格。

細粒度報告 輸出與測試性能之間是否存在這種張力的解決方案?

回答

0

的解決方案是使用包像https://github.com/LRDesign/rspec-steps

steps "Login and change password" do 
    it "should show the login form" do 
    visit root 
    page.should have_text "Login" 
    end 

    it "should successfully log in" do 
    fill_in :name, "Johnny User" 
    click "Login" 
    page.should have_text "Welcome, Johnny!" 
    end 

    it "should load the password change form" do 
    click "My Settings" 
    click "Update Password" 
    page.should have_selector("form#update_password") 
    end  

    it "should change the user's password successfully" do 
    fill_in :password, "foobar" 
    fill_in :password_confirmation, "foobar" 
    click "Change Password" 
    page.should have_text "Password changed successfully!" 
    User.find_by_name("Johnny User").valid_password?("foobar").should be_true 
    end 

end 

狀態保持它調用就可以測試之間如果你喜歡,可以選擇一系列步驟。

1

您可以使用before :all,它將在描述中的所有it塊之前運行給定塊一次。

如果您使用的是交易功能(在Rails中是默認的),您需要小心一點。在before :all中製作的插入內容不會回滾,並且您還應該使用.reload您創建的任何模型以防被測試修改。

(爲了完整起見,也有before :suite

文檔: https://www.relishapp.com/rspec/rspec-core/v/2-11/docs/hooks/before-and-after-hooks