2016-11-24 51 views
-2

我正在寫一個rspec /水豚測試,以確保表單中的輸入字段顯示正確的驗證。提高水豚測試的可讀性

我擔心我的代碼不太可讀。我如何重構這個以確保它是可讀的?

describe "#page" do 
    context "form validation" do 
    1.upto(4) do |index| 
     it "throws correct validation error when #{5-index} field(s) is (are) empty" do 
     login(page_path) 
     fill_in_form(index) 
     find('.button').trigger(:click) 
     expect(all('.form-error').count).to eq 5-index 
     all('.form-error')[-1...index-5].each do |error| 
      expect(error.text).to eq "#{@inputs[5-index][:error_message]} is required" 
     end 
     end 
    end 
    end 
end 


def fill_in_form(number_of_fields) 
    (0).upto(number_of_fields-1) do |i| 
    fill_in(@inputs[i][:name], :with => (@inputs[i][:value])) 
    end 
end 

def login(path) 
    visit(path) 
    # redirected to login 
    acceptance_login(@user) 
    visit(path) 
    # input fields 
    @inputs = [ 
    {name: 'first_name', error_message: "First name is not valid", value: "John"}, 
    {name: 'last_name', error_message: "Last name is not valid", value: "Doe"}, 
    {name: 'company', error_message: "Company name is not valid", value: "My company"}, 
    {name: 'role', error_message: "Role is not valid", value: "Developer"}, 
    {name: 'phone', error_message: "Phone number is not valid", value: "(800) 492-1111"} 
    ] 
end 
+1

相關方法調用組之間的空行是提高可讀性的一個步驟。像這樣的密碼塊很難讀取。 – tadman

+1

一件事是使用計數選項水豚提供,而不是使用對數(因爲它防止等待/重試,這將導致片狀測試)的當量匹配器。用 - 'all('。form-error',count:5-index)替換expect和all(..)。每個do | error | ... end',它將檢查'all'語句中正確的元素數目(如果需要,等待)。如果你只是想檢查正確的元素數量有那麼這將是'期待(頁)。爲了have_css(「形式的錯誤。」,數:5索引)',而不是預期(所有(.. 。)。count).to eq ...你正在使用。 –

+0

看看https://cucumber.io –

回答

1

你可以登錄的東西分離出來,成爲一個塊之前,並添加一些額外的換行符會作出即時的差異。

重新考慮需要循環遍歷表單。功能測試代價昂貴且速度慢,因此將其用作總覽以確保在窗體上執行了錯誤處理。

錯誤消息的具體實現,在所有相關的情況下,我會留給單元測試,因爲它們更快,更便宜。這樣你的功能測試就不會變得脆弱,如果你需要更改信息則更容易。