Home > database >  TypeError during assert_no_difference test
TypeError during assert_no_difference test

Time:02-21

The issue
I am writing unit tests for a RoR API, and I would like to test some entries from the response's body (something I have already done for another controller).
Basically, for an index method, I wanna check that every sub-element included in data share the same id as a specific one. Here is the complete test for the index method :

  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

But whatever I try, I get the very same error stack saying I have an issue with data type :

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>'

I really don't get why, since, as I said above, that's a check I've already done for some other controllers.

assert_equal @task.activity_id, json_response['data']['attributes']['activity_id']

What I have tried so far

  • convert both element from the assert_no_difference function to string (to_s) or to integer (to_i)
  • use assert_equal instead of assert_no_difference

CodePudding user response:

The error you are getting

TypeError: no implicit conversion of String into Integer

is commonly caused by trying to get a value from an array by a string index. For example, the following will raise the same error

a = [1, 2]
puts a['test']

In your case, I suspect json_response or json_response['data'] is an array.

Also, I believe you want to use assert_equal instead of assert_no_difference. assert_no_difference takes a numeric expression and a block; and asserts the expression is the same before and after the block is executed. https://api.rubyonrails.org/v7.0.2.2/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_difference

  • Related