2012-05-01 22 views
0

我在我的ruby腳本中使用了mysql2。 以此來測試對MySQL數據庫Mysql2響應不適用於在Ruby中收集的方法

該API響應是我的劇本的片段

test_job_by_id_5 
id = $data["jobs"]["id"][i] # example 5 
job = JobServices.job_by_id(id) 
response = @@con.query("select * from jobs where id = #{id}") #select * from jobs where id =5 
rs=response.collect #this fails 
assert_match(job[0]['title'],rs[0]['title'],"The title values are equal for #{$data["jobs"]["id"][i]}") 
end 

所以當我用這個與ruby 1.8.7 (2011-06-30 patchlevel 352) [i686-darwin10]它就像一個魅力

但是當我使用ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux]這是行不通的 我得到這個錯誤

NoMethodError: undefined method '[]' for 
#<Enumerator: #<Mysql2::Result:0x00000012d19f18>:collect> 

可不可以有一個人請^ h elp我解決這個問題?

+0

爲了清楚起見,我首先考慮在'assert_match'行中爲你的散列索引字符串使用單引號。 –

+0

我想我使用單引號,我不知道你的意思 – Amey

+0

也許再次看最後一個字符串,「標題值...」現在你知道我的意思了嗎? –

回答

1

當您在Enumerable(即Mysql2::Result)上調用collect時,會返回Enumerator實例。 Enumerator s沒有實現數組訪問操作符,所以你不能說enumerator[0]並得到任何有用的事情發生;然而,Enumerator不包括Enumerable這樣他們就以first迴應,所以你可能想這樣做:

rs = response.collect 
row = rs.first 
assert_match(job[0]['title'], row['title'], "The title values are equal for #{$data["jobs"]["id"][i]}") 

或者只是跳過Enumerator完全和在response呼籲first

row = response.first 
assert_match(job[0]['title'], row['title'], "The title values are equal for #{$data["jobs"]["id"][i]}") 

,甚至這:

row = @@con.query("select * from jobs where id = #{id}").first 
assert_match(job[0]['title'], row['title'], "The title values are equal for #{$data["jobs"]["id"][i]}") 

請記住,row.nil?將是如果您的查詢沒有找到任何內容,則爲true,因此如果您不想要異常,則可能需要考慮這一點。

+0

感謝您的迴應,這可能會做到這一點,但我需要遍歷返回的所有行,並且我不知道將返回多少行?使用'each',而不是在數據庫響應中執行'each',我需要爲每個API響應執行此操作。所以我不確定是否有'second'和'third' – Amey

+0

@perlnewbie:我不確定你的意思,但也許你可以把它從內部轉出或者將所有結果提取到一個數組中,然後迭代作業'和陣列同時。 –

+0

我的意思是如果我做'響應[0] ['標題']'不使用收集它不起作用。因此,如果我做'job.each do | i |,那麼基本上不能在同一個循環中迭代作業和響應assert_match(job [i] ['title'],response [i] ['title'])end' – Amey