Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ohbarye opened this issue Oct 22, 2022 · 2 comments

Comments

@ohbarye
Copy link

ohbarye commented Oct 22, 2022

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,

  • the bad pattern slightly increases cognitive load that forces me to build actual URLs in my mind.
  • the bad pattern sometimes discourages Test Driven Development.
    • In TDD, a test comes first. At this point, I know actual URL but I don't know the named routes because the routes.rb has not been edited yet. (=I don't care about named routes at that moment).

Possible Objection

named routes possibly have merits in some points.

  • You don't have to edit test cases when you edit routes.rb. It automatically follows up.
  • It could be consistent to use named routes in tests if you use named routes in production code.

References

@pirj
Copy link
Member

pirj commented Oct 27, 2022

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

This comment was marked as off-topic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants