简体   繁体   English

RSpec 生成请求规范而不是控制器规范

[英]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/.我正在使用 rspec-rails,但我想在调用rails g controller Blahs时进行更改,我希望创建 spec/requests/,而不是 spec/controllers/。

Thanks!谢谢!

rails g integration_test foo

一切顺利!

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.这里有一些解释:测试框架的钩子设置在 ControllerGenerator 内部,所以我们需要加载类来覆盖值。 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. config.generators块也为控制台和服务器运行,所以它不合适。 There is also self.generators block, but it runs before config.generators and generator will be not configured.还有self.generators块,但它在config.generators之前运行,并且生成器不会被配置。 So I've found Engine#load_generators method, which fits for me.所以我找到了适合我的Engine#load_generators方法。

Tested with rails 5.0.1.使用 Rails 5.0.1 进行测试。

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我认为您实际上无法配置它,但您始终可以分叉 rspec-rails 并根据自己的喜好对其进行调整https://github.com/rspec/rspec-rails/blob/master/lib/generators/rspec/controller/ controller_generator.rb

Good luck!祝你好运!

There is a RSpec generator to generate request specs:有一个 RSpec 生成器来生成请求规范:

rails g rspec:request Foo

Note that in order to enable RSpec generators you need to place the following code in your application.rb :请注意,为了启用 RSpec 生成器,您需要在application.rb放置以下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM