ruby-on-rails - 请求规范按预期工作; Controller 规范允许 :post when it shouldn't

标签 ruby-on-rails rest rspec2 controllers

为什么这个请求规范能够正常工作:

require "spec_helper"

describe "POST on a GET route" do
  it "should not allow this" do
    post "/applicants/new"
    assert_response :missing
  end
end

但在此 Controller 规范中,GET、POST、PUT 和 DELETE 的工作方式相同,但它们不应该工作:

require 'spec_helper'

describe ApplicantsController do
  it "should not allow this" do
    post :new
    should respond_with :missing # but it responds with 200
  end
end

更新:添加了 ApplicantsController 代码和路由定义:

class ApplicantsController < InheritedResources::Base    
  respond_to :html
  actions :index, :new, :create

  def new
    if current_user
      redirect_to resume_application_path and return
    end

    @applicant = Applicant.new
    @applicant.applications.build
    @applicant.build_user_detail
    new!
  end    
end

路线:

resources :applicants

更新:经过大量研究和深入研究 API,我相信这是设计使然,因为 Controller 规范继承自 ActionController::TestCase,而请求规范继承自 ActionDispatch::IntegrationTest。对于 Controller 规范,HTTP 动词仅具有描述性。

有人可以确认这是设计使然吗?或者我应该提交错误报告吗?

谢谢!

最佳答案

这似乎令人惊讶,但是当您从单独测试 Controller 操作的角度来看它时,这是有道理的。通常, Controller 操作不需要了解 HTTP 请求方法。指定没有方法的路由说明了这一点:

  match 'sample' => 'applicants#index'

现在 GET/samplePOST/sample 都将路由到索引操作。除非您为其编写代码,否则 Controller 将不知道 GET 和 POST 请求之间的区别。 Controller 规范不测试请求方法/操作组合是否可路由,因为这是路由引擎的责任。

您可以使用路由规范验证哪些路由有效,哪些无效:

it "recognizes and generates #new" do
  { :get => "/applicants/new" }.should route_to(:controller => "applicants", 
      :action => "new")
end

it "does not recognize POST /applicants/new" do
  { :post => "/applicants/new" }.should_not be_routable
end

关于ruby-on-rails - 请求规范按预期工作; Controller 规范允许 :post when it shouldn't,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5227999/

相关文章:

ruby-on-rails - 使用 Mina 和 Foreman 正确部署 Rails 应用程序

ruby-on-rails - 多个belongs_to到同一个表

http - 使用本地 http 调用的开销

javascript - 使用 Firestore REST API 在 StructuredQuery 中设置 'orderBy'

javascript - 如何在 rails 变量中获取 Javascript 变量

ruby-on-rails - Rails 路由和 Controller 模块-命名空间?

c# - RestSharp 反序列化为 List<MyClass>

ruby-on-rails - ActionMailer::Base.deliveries 在 Rspec 中始终为空

ruby-on-rails - 未定义方法relative_url_root为零:NilClass when running rspec on namespaced controller

hash - 尝试模拟哈希元素的获取和放置时,RSpec 无法定义单例错误