使用rails的"post"在具有路由范围和协议的rspec中的控制器测试中 [英] Using rails' "post" in controller tests in rspec with scoping and protocol on routes

查看:53
本文介绍了使用rails的"post"在具有路由范围和协议的rspec中的控制器测试中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails项目,该项目在生产环境中的基本URL的子目录中用完了,我希望它在dev中采取这种方式,以便使dev和prod尽可能接近.我已经设置了路由文件,如下所示:

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:

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是这样的:

My CatsController is like this:

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测试:

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

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://"}

推荐答案

问题是:protocol的值有点奇怪.

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

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:

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

或您的协议可能是什么.

or whatever your protocol might be.

这篇关于使用rails的"post"在具有路由范围和协议的rspec中的控制器测试中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆