How do I generate a controller spec using rspec?
If you are using Rails 3 + rspec and you installed rspec (rails g rspec:install
), it should generate controller specs for each controller you generate (and others objects).
If you need to create one by hand. Just create a new new_controller_name_spec.rb
in your spec/controllers
.
require 'rails_helper'
describe NewControllerName do
# Test!
end
You could also try to re-generate the controller file, say No when it asks you if you want to overwrite the existing controller, and hopefully it will regenerate the rspec for that controller again.
the rspec way is
rails g rspec:controller passwords
it gives
create spec/controllers/passwords_controller_spec.rb
--Update
You can configure your application to generate rspec when model or controller is created. Add to config/application.rb
# don't generate RSpec tests for views and helpers.
config.generators do |g|
g.test_framework :rspec, fixture: true
g.fixture_replacement :factory_girl, dir: 'spec/factories'
g.view_specs false
g.helper_specs false
end
$rails g model category
invoke mongoid
create app/models/category.rb
invoke rspec
create spec/models/category_spec.rb
invoke factory_girl
create spec/factories/categories.rb
$rails g controller categories
create app/controllers/categories_controller.rb
invoke haml
create app/views/categories
invoke rspec
create spec/controllers/categories_controller_spec.rb
invoke helper
create app/helpers/categories_helper.rb
invoke rspec
invoke assets
invoke coffee
create app/assets/javascripts/categories.js.coffee
invoke scss
create app/assets/stylesheets/categories.css.scss
As of Rails 5 and RSpec 3.5, controller spec files are no longer the recommended approach, instead RSpec creates files called requests. These files test the output of your controllers by testing what happens when a request is made to a given URL.
Consider the following:
rails g rspec:controller fruits
Pre-Rails 5 you would get a file like:
spec/controllers/fruits_controller_spec.rb
With Rails 5 you would get a file like:
spec/requests/fruits_request_spec.rb
The RSpec 3.5 release notes have more to say on this:
The official recommendation of the Rails team and the RSpec core team is to write request specs instead. Request specs allow you to focus on a single controller action, but unlike controller tests involve the router, the middleware stack, and both rack requests and responses. This adds realism to the test that you are writing, and helps avoid many of the issues that are common in controller specs.
Hope this helps anyone who stops by because they were trying to figure out why Rails wasn't making controller specs!