2012-04-07 20 views
2

我正在使用Ruby on Rails 3.2.2和rspec-rails-2.8.1。我想輸出關於將要運行測試的詳細信息,例如,像這樣:輸出有關將要運行的測試的更多信息是否正確?

# file_name.html.erb 
... 

# General idea 
expected_value = ... 

it "... #{expected_value}" do 
    ... 
end 

# Usage that I am trying to implement 
expected_page_title = 
    I18n.translate(
    'page_title_html' 
    :user => @user.firstname 
) 

it "displays the #{expected_page_title} page title" do 
    view.content_for(:page_title).should have_content(expected_page_title) 
end 

:「輸出」旨在爲那些輸出,當您運行rspec . --format documentation命令行在終端窗口中。

這是一種正確的測試方式嗎?


相關問題:

回答

0

你的問題是要徵求了一些意見,但我會嘗試用一些例子證明我的。

簡短回答:不,這不是你應該如何寫RSpec(或任何測試)的描述。這是非常規的,並且不會爲額外的代碼增加太多價值。

龍回答:RSpec的是,旨在幫助描述在同一時間你的代碼的行爲和意圖爲編寫自動化測試一個BDD(行爲驅動開發)工具。當您考慮代碼的行爲時,是否將預期結果添加到測試描述中確實增加了很多價值?如果是這樣,也許你應該重新考慮你正在測試的東西。

例如,假設你有一個User類,你要測試的是串接一個用戶的名字和姓氏的方法:

describe User do 
    expected_full_name = 'Software Guy' 

    subject { User.new(first: 'Software', last: 'Guy') } 

    it 'should have the full name #{expected_full_name}' do 
    subject.full_name.should == 'Software Guy' 
    end 
end 

VS

describe User do 
    subject { User.new(first: 'Software', last: 'Guy') } 

    it 'should have a full name based on the first and last names' do 
    subject.full_name.should == 'Software Guy' 
    end 
end 

在第一次測試,什麼在描述中是否有預期的結果真的會買你?它是否告訴你任何有關用戶預期的行爲?不是真的。

舉一個例子。如果我來到您的項目並看到類似的測試說明,我會感到困惑,因爲它沒有真正告訴我測試的內容。我仍然需要查看代碼以瞭解發生了什麼。比較這兩個例子:

it "displays the #{expected_page_title} page title" do 
    view.content_for(:page_title).should have_content(expected_page_title) 
end 

這將使你在喜歡的控制檯的東西:

「顯示我真棒標題頁標題」

與此相比,:

it "should translate the page title" do 
    view.content_for(:page_title).should have_content(expected_page_title) 
end 

這在控制檯中與在測試中完全相同:

「應該翻譯頁面標題」

你顯然可以自由選擇你想要的任何一個,但我從幾年的測試經驗來說,並強烈建議你不要這樣做。

+0

在您的第一個RSpec示例中,您使用了'subject.full_name.should =='Software Guy'',但是我會使用'subject.full_name.should == expected_full_name'來幹DRY(不要重複自己)。 – Backo 2012-04-07 19:17:58

相關問題