Robert Ross
Robert Ross

Reputation: 1925

RSpec generate request spec instead of controller spec

I'm using rspec-rails but I'd like to change when rails g controller Blahs is invoked, I'd like spec/requests/ to be created, instead of spec/controllers/.

Thanks!

Upvotes: 10

Views: 5037

Answers (4)

Pere Joan Martorell
Pere Joan Martorell

Reputation: 3103

There is a RSpec generator to generate request specs:

rails g rspec:request Foo

Note that in order to enable RSpec generators you need to place the following code in your application.rb:

class Application < Rails::Application
  ...
  config.generators do |g|
    g.test_framework :rspec
  end
end

Upvotes: 3

prcu
prcu

Reputation: 1013

Seems like there is no usual way to achieve this, however I've found monkey-patching solution:

# config/initializers/generators.rb
Rails.application.configure do
  config.generators do |g|
    # your setup here, like g.javascripts = false
  end

  def self.load_generators(*)
    super
    require 'rails/generators/rails/controller/controller_generator'
    Rails::Generators::ControllerGenerator.class_eval do
      remove_hook_for :test_framework
      hook_for :test_framework, as: :request
    end
  end
end

Here is some explanation: hook for test framework is set right inside ControllerGenerator, so we need to load the class to override the value. I don't want to load this class in any case other than running generators. config.generators block runs for console and server too, so it's not appropriate. There is also self.generators block, but it runs before config.generators and generator will be not configured. So I've found Engine#load_generators method, which fits for me.

Tested with rails 5.0.1.

Upvotes: 6

DVG
DVG

Reputation: 17480

rails g integration_test foo

And you're good to go!

Upvotes: 17

Renra
Renra

Reputation: 5649

I don't think you can actually configure this but you can always fork rspec-rails and tweak it to your liking https://github.com/rspec/rspec-rails/blob/master/lib/generators/rspec/controller/controller_generator.rb

Good luck!

Upvotes: 0

Related Questions