0

So I recently pulled in the Rails best practices gem and it said I should use the current_user.find instead of doing it a different way. The issue is, this of course throws ActiveRecord::RecordNotFound when the current_user doesn't have the record. Now in my integration tests, I explicitly test that a user cannot access another users records. This causes the error to be thrown. The issue is, I want to handle this error since I expect it to be thrown. It's currently making my tests red. How can I get my tests to go green, while still testing that the error is thrown? Any help is clarification on best practices would be greatly appreciated! Thank you!

sidenote

As you can see, I'm attempting to use assert_raise. Which isn't catching the error of course... And assert_field_no_difference is just one of my helper methods..

Also, I've been searching for answers for a while now. Most people address how to handle it within the controller, in respect to render a page, or redirecting, but I haven't found anyone addressing how to handle it as expected behavior within a test.

my integration test

test "tries to edit resource not associated with user" do
  login(@user)


  assert_field_no_difference @resource, 'url' do
    assert_raise ActiveRecord::RecordNotFound do
      put community_resource_path(@resource), params: { community_resource: {
      url: 'http://www.example.com'}}
    end
  end
end

error being thown as expected

Error:
Community::ResourcesFlowsTest#test_tries_to_edit_resource_not_associated_with_user:
ActiveRecord::RecordNotFound: Couldn't find Community::Resource with 'id'=1 [WHERE "community_resources"."user_id" = $1] 
  app/controllers/community/resources_controller.rb:106:in `set_allowable_access_resource' 
  test/integration/community/resources_flows_test.rb:110:in `block in <class:ResourcesFlowsTest>'
  • you want the user (who doesn't have access) to receive a 500 error? – Anthony Oct 22 '17 at 23:39
  • 1
    Possible duplicate of [Rails ActiveSupport: How to assert that an error is raised?](https://stackoverflow.com/questions/3454925/rails-activesupport-how-to-assert-that-an-error-is-raised) – max pleaner Oct 23 '17 at 04:04
  • Do you get the same issue if you move the `assert_raise` out of the `assert_field_no_difference` block? My best guess is `assert_field_no_difference` is causing the issue, as everything else seems fine to me. – henrebotha Oct 23 '17 at 08:26
  • So I deleted the assert_field_no_difference, and left the assert_raise, still throwing the error. I'm assuming I have to catch it within the controller huh? And Max Pleaner, it's not a duplicate, it's a different application of testing for an exception being raised.. I've already reviewed that post. And as you can see, I'm using that method, but the error is still being thrown and making my test red. – Drew Rodrigues Oct 23 '17 at 17:13

0 Answers0