我正在為 RoR API 撰寫單元測驗的問題
,并且我想測驗回應正文中的一些條目(我已經為另一個控制器做了一些事情)。
基本上,對于一種index方法,我想檢查包含在其中的每個子元素data是否與特定的子元素共享相同的 id。這是該index方法的完整測驗:
test "should access Membership index - specifix team" do
get api_v1_team_memberships_url(@team),
headers: { Authorization: JsonWebToken.encode(user_id: @user.id) },
as: :json
assert_response :success
json_response = JSON.parse(self.response.body)
assert_no_difference @membership.member_id, json_response['data']['attributes']['member_id']
end
但無論我嘗試什么,我都會得到相同的錯誤堆疊,說我有資料型別問題:
Error:
Api::V1::MembershipsControllerTest#test_should_access_Membership_index_-_specifix_team:
TypeError: no implicit conversion of String into Integer
test/controllers/api/v1/memberships_controller_test.rb:20:in `[]'
test/controllers/api/v1/memberships_controller_test.rb:20:in `block in <class:MembershipsControllerTes
t>'
我真的不明白為什么,因為,正如我上面所說,這是我已經為其他一些控制器完成的檢查。
assert_equal @task.activity_id, json_response['data']['attributes']['activity_id']
到目前為止我嘗試過的
- 將
assert_no_difference函式中的兩個元素都轉換為字串 (to_s) 或整數 (to_i) - 使用
assert_equal而不是assert_no_difference
uj5u.com熱心網友回復:
你得到的錯誤
TypeError: no implicit conversion of String into Integer
通常是由于試圖通過字串索引從陣列中獲取值而引起的。例如,以下將引發相同的錯誤
a = [1, 2]
puts a['test']
在你的情況下,我懷疑json_responseorjson_response['data']是一個陣列。
另外,我相信您想使用assert_equal而不是assert_no_difference. assert_no_difference接受一個數值運算式和一個塊;并斷言執行塊之前和之后的運算式是相同的。https://api.rubyonrails.org/v7.0.2.2/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_difference
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429656.html
上一篇:SpringBoot-SpringSecurity-InvalidBearerTokenException錯誤處理
