Reputation: 3090
In an integration test I have:
get activation_path("invalid token")
assert flash[:danger]
assert_redirected_to root_path
The activation_path
refers to a path where a token gets validated. A correct path would look like: get activation_path("valid token", inv: '10')
. So in the test, the link does not contain a value for inv
and thus is an invalid link. The controller method uses the inv
to find the invitation:
@invitation = Invitation.find(params[:inv])
So the expected behavior is that the invalid link produces a flash error and a redirect. However, the first line of the test fails with as error:
ActiveRecord::RecordNotFound: Couldn't find Invitation with 'id'=
This refers to the first line of the controller method, which as mentioned is:
@invitation = Invitation.find(params[:inv])
Why is the test failing? I would expect it to just return nil
for @invitation
but instead it generates the error. How should I adjust (the controller method?) to take into account users submitting such invalid links?
Update: I've also tried:
get activation_path("valid token", inv: '88888888888')
assert flash[:danger] # There's no invitation with that number
assert_redirected_to root_path
This test as well fails pointing to the same first line of the controller method:
ActiveRecord::RecordNotFound: Couldn't find Invitation with an out of range value for 'id'
Upvotes: 1
Views: 49
Reputation: 3842
Per the Rails docs:
The find method will raise an ActiveRecord::RecordNotFound exception if no matching record is found.
By default, Rails responds to an ActiveRecord::RecordNotFound
error by rendering a 404 response in production and staging. This is typically the desired response when a user visits a URL for a non-existent record.
If you want it to return nil
instead of raising an error, use find_by_id
instead:
Invitation.find_by_id 0
=> nil
Upvotes: 1