在rspec的控制器测试中使用rails的“post”,在路由上使用范围和协议

时间:2022-10-11 23:25:48

I have a rails project that is running out of a subdirectory of the base url in production and I want it to act that way in dev so as to make dev and prod as close as possible. I have the routes file set up like so:

我有一个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

My CatsController is like this:

我的CatsController是这样的:

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

I want to test my Create Cat Method, so I set up an rspec test in spec/controllers/cats_controller_spec.rb:

我想测试我的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

When I run my test, though, I get

当我运行测试时,我得到

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

Rake routes says my route is there! What is going on under the hood here, and why is this failing?

耙路说我的路在那儿!引擎盖下面发生了什么,为什么会失败?

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

2 个解决方案

#1


3  

The problem is that the value of :protocol is a bit wonky.

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

The better way to fix this, I think, is to set the protocol in your scopes to http instead of http://. If you did need to test your controller with some funky protocol, though, you should be able to do:

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

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

or whatever your protocol might be.

或者任何你的协议。

#2


0  

For rspec 3, this below works for me.

对于rspec 3,以下对我是有效的。

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

#1


3  

The problem is that the value of :protocol is a bit wonky.

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

The better way to fix this, I think, is to set the protocol in your scopes to http instead of http://. If you did need to test your controller with some funky protocol, though, you should be able to do:

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

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

or whatever your protocol might be.

或者任何你的协议。

#2


0  

For rspec 3, this below works for me.

对于rspec 3,以下对我是有效的。

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