2014-09-23 57 views
0

我正在編寫一個步驟定義,將採取http請求類型(get,post等),api的url以及從小黃瓜發送的數據表。我以如下方式實現它,但它是一種非常迫切的風格,對於其他測試人員而言並不一定很清楚發生了什麼。它構建從表像這樣使我的步驟定義更漂亮

| x | y | 
| 1 | 2 | 
| 5 | 7 | 

使得請求使用JSON,在這種情況下,兩個被髮送,用下面的JSON發送的請求:

{ 
    "x":"1" 
    "y":"2" 
} 

{ 
    "x":"5" 
    "y":"7" 
} 

換句話說,第一行之後的每一行表示一個請求,其中包含來自第一行的變量的特定值。

我的實現如下,更可讀的重構是受歡迎的。謝謝。

When(/^I submit the following (?:in)?valid data in a "(.*?)" request to "(.*?)"$/) do |request_type, api, table| 
    data = table.raw 
    for i in 1...data.length #rows 
    body = {} 
    for j in 0...data[0].length #cols 
     body[data[0][j]] = data[i][j] 
    end 
    @response = HTTParty.__send__ request_type, "https://stackoverflow.com/a/url#{api}", { 
     :body => body.to_json, 
     :headers => { 'Content-Type' => 'application/json' } 
    } 
    end 
end 

回答

1

我會寫這樣的事:

When(/^I submit the following (?:in)?valid data in a "(.*?)" request to "(.*?)"$/) do |method, api, table| 
    data = table.raw 
    keys = data.shift 

    data.each do |line| 
    hash = Hash[*keys.zip(line)] 
    @response = build_request(api, method, hash) 
    end 
end 

# with this helper method 
def build_request(api, method, hash) 
    HTTParty.__send__(method, 
        "https://stackoverflow.com/a/url#{api}", 
        { :body => hash.to_json, 
         :headers => { 'Content-Type' => 'application/json' } }) 
end 
+0

的helper方法是一個明確的加分。我會檢查一下,看起來我會在路上更多地瞭解Ruby。 – Cohen 2014-09-24 11:31:00