RSpec控制器规范表现得像请求规范

3
  • Rails 5.0.0.rc1
  • rspec-core@a99ff26
  • rspec-rails@052206f

我有一个控制器规范,大致如下:

require "rails_helper"

RSpec.describe InquiriesController, type: :controller do
  describe "#create" do
    let(:inquiry_attributes) { attributes_for(:inquiry) }

    before do
      post :create, inquiry: inquiry_attributes
    end

    it "whatever" do
      expect(2).to be 2
    end
  end
end

这段代码位于spec/controllers/inquiries_controller_spec.rb,因此RSpec不应该根据其位置推断它是一个请求(spec)测试。
当我运行这个测试时,我得到以下错误:
1) InquiriesController#create whatever
   Failure/Error: post :create, inquiry: inquiry_attributes

   URI::InvalidURIError:
     bad URI(is not URI?): create
     # /Users/spetryk/.gem/ruby/2.3.1/gems/rack-test-0.6.3/lib/rack/test.rb:193:in `env_for'
     # /Users/spetryk/.gem/ruby/2.3.1/gems/rack-test-0.6.3/lib/rack/test.rb:66:in `post'

嗯,看起来post是来自Rack。不确定原因。这里是我的spec_helper和rails_helper:

spec_helper.rb

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.filter_run focus: true
  config.run_all_when_everything_filtered = true
end

rails_helper.rb

ENV["RAILS_ENV"] ||= "test"
require File.expand_path("../../config/environment", __FILE__)

abort("The Rails environment is running in production mode!") if Rails.env.production?

require "spec_helper"
require "rspec/rails"
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  config.use_transactional_fixtures = true

  # Yes, I've tried removing this line
  config.infer_spec_type_from_file_location!

  config.filter_rails_from_backtrace!

  config.include Rails.application.routes.url_helpers
  config.include FactoryGirl::Syntax::Methods
end

我的InquiriesController位于app/controllers/inquiries_controller.rb,不属于任何一个模块,并且路由已正确连接(我通过手动访问并检查其工作来验证了这一点)。该方法确实被命名为create,我以前在其他项目中也成功地使用过。


1
值得一提的是,将 :create 改为 /inquiries 可以使规范通过。 - Steven Petryk
48小时后,您可以接受自己的答案。请参阅http://stackoverflow.com/help/self-answer - Holger Just
@HolgerJust 我知道,但我想避免人们浪费时间看这个 :) - Steven Petryk
1个回答

0
我找到了问题所在。我不经意地复制了一个公司标准的spec_helper,其中包括Rack::Test::Methods,将Rack方法注入到了所有的测试中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接