加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 测试无法直接访问的RSpec控制器操作

发布时间:2020-12-17 01:21:52 所属栏目:百科 来源:网络整理
导读:我有一个无法直接访问的控制器,采用传统的RESTful方式,而只是通过特定的URL. 通常我习惯在我的控制器规范中使用get和post来调用控制器动作.有没有办法通过访问特定网址来运用我的控制器? 编辑: 这是我的路线: Larzworld::Application.routes.draw do matc
我有一个无法直接访问的控制器,采用传统的RESTful方式,而只是通过特定的URL.

通常我习惯在我的控制器规范中使用get和post来调用控制器动作.有没有办法通过访问特定网址来运用我的控制器?

编辑:

这是我的路线:

Larzworld::Application.routes.draw do

  match '/auth/:provider/callback' => 'authentications#create'

  devise_for :users,:controllers => {:registrations => "registrations"} 

  root :to => 'pages#home'
end

这是我的规格:

require 'spec_helper'

describe AuthenticationsController do

before(:each) do
  request.env["omniauth.auth"] = {"provider" => "twitter","uid" => "12345678"} 
end

describe 'POST create' do

  it "should find the Authentication using the uid and provider from omniauth" do
    Authentication.should_receive(:find_by_provider_and_uid)
    post 'auth/twitter/callback'
  end
end

end

这是我收到的错误:

Failures:
  1) AuthenticationsController POST create should find the Authentication using the uid and provider from omniauth
    Failure/Error: post 'auth/twitter/callback'
    No route matches {:action=>"auth/twitter/callback",:controller=>"authentications"}
    # ./spec/controllers/authentications_controller_spec.rb:13

Finished in 0.04878 seconds
1 example,1 failure

解决方法

无论您的控制器是否为RESTful,控制器测试都使用四个HTTP谓词(GET,POST,PUT,DELETE).所以如果你有一个非RESTful路由(Rails3):

match 'example' => 'story#example'

这两个测试:

require 'spec_helper'

describe StoryController do

  describe "GET 'example'" do
    it "should be successful" do
      get :example
      response.should be_success
    end
  end

  describe "POST 'example'" do
    it "should be successful" do
      post :example
      response.should be_success
    end
  end

end

将通过,因为路线接受任何动词.

编辑

我认为你正在混淆控制器测试和路由测试.在控制器测试中,您要检查操作的逻辑是否正常工作.在路由测试中,您检查URL是否转到正确的控制器/操作,并且正确生成了params哈希.

因此,要测试您的控制器操作,只需执行:

post :create,:provider => "twitter"`

要测试路由,请使用params_from(对于Rspec 1)或route_to(对于Rspec 2):

describe "routing" do
  it "routes /auth/:provider/callback" do
    { :post => "/auth/twitter/callback" }.should route_to(
      :controller => "authentications",:action => "create",:provider => "twitter")
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读