2014-09-23 59 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