Skip to content

Proposal: Add cop to prevent mocking Rails find_by #2122

@hlascelles

Description

@hlascelles

This is a feature proposal. Take the following code:

# Code
def show
  @user = User.find_by(params[:idq])
end

# Spec
test_user = User.create
expect(User).to receive(:find_by).and_return(user)
# ... more code

In this case, the developer has made their lives easier in the spec by simply giving themselves the test_user object they want to work on.

However, they have hidden the fact that the params lookup is a dud, using idq and not id.

The correct thing to do is set up the DB correctly with the user, then get the test code to exercise the lookup properly.

Describe the solution you'd like

I would like to prevent receive(:find_by) and its variants, and receive(:where) and similar.

Describe alternatives you've considered

Telling the team not to do this. But, I'd prefer a bot to do it :)

Additional context

I am unsure if this ticket should go in rubocop-rspec or rubocop-rails, so apologies if this is the wrong place!

I can have a go if you agree it might be useful?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions