rubocop / rails-style-guide

A community-driven Ruby on Rails style guide
http://rails.rubystyle.guide
6.47k stars 1.06k forks source link

Suggestion: Use string literals instead of named routes or URL helpers in tests #328

Open ohbarye opened 1 year ago

ohbarye commented 1 year ago

Hi. This is a proposal about named routes usage in tests. I'd like to hear what you think.

Proposal

Use string literals instead of named routes or URL helpers in tests.

# bad
get photos_path
get photo_path(id)
get edit_photo_path(id)
# good
get "/photos"
get "/photos/#{id}"
get "/photos/#{id}/edit"

and so on.

Reason

Integration test (e.g. request specs, system specs) is to mimic user eyes and actions. A user could see "/photos", but not "photos_path". I agree with the following idea.

The more your tests resemble the way your software is used, the more confidence they can give you. https://twitter.com/kentcdodds/status/977018512689455106

From a programmer's view,

Possible Objection

named routes possibly have merits in some points.

References

pirj commented 1 year ago

There's some controversy there in the Rails Testing Rails Applications guide.

Integration:

class BlogFlowTest < ActionDispatch::IntegrationTest
  test "can see the welcome page" do
    get "/"

System:

class ArticlesTest < ApplicationSystemTestCase
  test "viewing the index" do
    visit articles_path

Wondering why is it so.

If you don't write route tests and use URL helpers in system/integration, the mapping is not covered. It is risky to have a green CI after changing routes.

RoshanNair22 commented 1 year ago

I agree with all the responses. But we all have our own way of solving our problems, right? Yeah, so get on with it.

Also, FYI, if any of our curious readers want to know more about test driven development, please read the blog written my colluagues.

moznion commented 4 weeks ago

I completely agree with this suggestion. Has there been any progress on it?

pirj commented 4 weeks ago

Would you like to send a pr to kick start tims, @moznion ?

moznion commented 3 weeks ago

@pirj Thank you for your suggestion. Why not, I'll work on it.

moznion commented 2 weeks ago

@pirj Hi, I just sent a pull request to this repo #359, and the actual cop implementation is here (not yet pull-requested): https://github.com/rubocop/rubocop-rails/compare/master...moznion:rubocop-rails:http-url?expand=1

What do you think about them?