Question

I'm new to Ruby (RoR) and rspec.

I have the basic project scaffold and a controller within project/app/controllers/books_controller.rb

Then I'm trying to setup rspec in project/spec/controllers/book_spec.rb

There also exists project/spec/spec_helper.rb that book_spec.rb requires. This file is where I'm trying to include the books_controller.rb file.

How do I include the books_controller.rb file so book_spec.rb has the Book object so when I run rspec, it works?

Currently I've tried things like require_relative "../app/controllers/books_controller" and it doesn't work. It gives me an error like:

uninitialized constant ApplicationController ... in 'require_relative'

Any help would be great.

Was it helpful?

Solution

You don't need to manually include your controllers, just follow the rspec naming conventions and describe the desired object and everything will work fine.

Your controller spec should be named books_controller_spec.rb. That is the exact same name as your controller with a _spec added at the end. This is not a hard requirement but a highly suggested convention as a book_spec.rb really implies a Book model spec rather than a controller.

The critical part is that in your spec you describe the desired object, e.g.

describe BooksController do
  #...
end

You might also want to have a look at the rspec-rails gem which provides some useful generators for specs. Ideally you integrate with Rails so whenever you generate a new model or controller a new spec is created for you as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top