【问题标题】:Using rails' "post" in controller tests in rspec with scoping and protocol on routes在 rspec 的控制器测试中使用 rails 的“post”,并在路由上使用范围和协议
【发布时间】:2013-04-09 19:59:58
【问题描述】:

我有一个 rails 项目在生产中用完了基本 url 的子目录,我希望它在 dev 中以这种方式运行,以使 dev 和 prod 尽可能接近。我的路由文件设置如下:

Foo::Application.routes.draw do
    def draw_routes
        root :to=>'foo#home'
        resources :cats, :only=>[:create] do
    end
    if Rails.env.production?
        scope :protocol=>'http://' do
            draw_routes
        end
    else
        scope :path=>"/foo", :protocol=>'http://' do
            draw_routes
        end
    end
end

我的 CatsController 是这样的:

class CatsController < ApplicationController
    def create
        @cat = Cat.new(:name=>"Bob")
        if @cat.save()
            redirect_to root
        end
    end
end

我想测试我的 Create Cat 方法,所以我在 spec/controllers/cats_controller_spec.rb 中设置了一个 rspec 测试:

require 'spec_helper'
describe CatsController do
    describe "calling create cat with good data" do
        it "should add a cat" do
            expect {post(:action=>:create)}.to change(Cat, :count).by(1)
        end
    end 
end

但是,当我运行测试时,我得到了

Failure/Error: post :create
     ActionController::RoutingError:
       No route matches {:controller=>"cats", :action=>"create"}
     # ./spec/controllers/cats_controller_spec.rb:5:in `(root)'

Rake 路线说我的路线在那里!这里面到底发生了什么,为什么会失败?

Rake Routes:
    cats POST   /foo/cats(.:format)            cats#create {:protocol=>"http://"}

【问题讨论】:

  • 改用post '/foo/cats'
  • No dice: post 'foo/cats' 产生 ActionController::RoutingError: No route matches {:controller=>"cats", :action=>"foo/cats"} 不过谢谢!
  • 如果你去http://localhost:3000/foo/cats,去预期的地方?
  • 如果我在浏览器中去那里,是的。此外,如果我有一个发布请求的表单,并且我将其称为 post)%>,它也会发送到正确的位置。
  • 嗯。如果我删除 :protocol 它开始工作,所以它与此有关。

标签: ruby-on-rails ruby rspec jruby rspec-rails


【解决方案1】:

问题是:protocol 的值有点不稳定。

我认为解决此问题的更好方法是将您范围内的协议设置为http 而不是http://。但是,如果您确实需要使用一些时髦的协议来测试您的控制器,您应该可以这样做:

post(:action => :create, :protocol => 'funky')

或任何您的协议。

【讨论】:

  • 我必须补充一点,是的,正确的协议是没有斜杠的“http”。但是,我仍然必须在 post 函数中明确指定它。不过现在可以使用了!
【解决方案2】:

对于 rspec 3,以下内容适用于我。

post :action, protocol: 'https://'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多