Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would you need to do to Rails to make spec files live alongside the code they describe?

For years I've followed the rails convention of putting spec files in a spec folder and entirely separate from the code they describe:

- app
  - controllers
    - application_controller.rb
  - models
    - user.rb
- spec
  - controllers
    - application_controller_spec.rb
  - models
    - user_spec.rb

However there's a lot of unnecessary dislocation and confusion that can come with that approach and I really like Angular's approach of keeping components, their specs and code side by side. Having worked on large rails projects, the dislocation between spec and code can become incredibly confusing and disorientating.

What changes would be needed to make this happen?

I'd like to experiment doing the same thing in rails and moving the specs to sit next to the files they describe so that the directory structure is more similar to this:

- app
  - controllers
    - application_controller.rb
    - application_controller_spec.rb
  - models
    - user.rb
    - user_spec.rb

What things will I need to change to make this work?

A couple of things that spring to mind are:

  • making sure Zeitwerk doesn't load spec files into memory on app load
  • adjusting guard so that it watches the correct directories

What other things would I need though and is there anything in particular I should watch out for?

like image 776
Peter Nixey Avatar asked Jul 20 '20 13:07

Peter Nixey


1 Answers

It may be possible, but probably not practical.

First off, assuming you're using rspec, you would have to configure/override the path where your test suite expects to find your spec files, which is probably not all that difficult to do, but if you're using any extensions to rspec, (or any other test suite), you would have to make adjustments to any references to spec paths in order to make your specs run correctly, which could add to future maintenance efforts.

You may also lose the ability to use generators, unless you patch the classes that create spec files when you run a generator, since they will, by default, put spec files in spec/models, spec/controllers, etc.

Overriding these kinds of things is possible, but will require maintenance, and would probably be considered 'not the Rails way' by most Rails developers. Rails is an opinionated framework, which is to say that any developers working on your app would almost certainly expect to see spec files in the spec directory by default, so you might get pushback from your future team members.

There may be other issues, but those are just the first things that come to mind.

like image 187
NM Pennypacker Avatar answered Nov 07 '22 07:11

NM Pennypacker