问题描述
我有一个控制器,它不能以传统的 RESTful 方式直接访问,而只能通过特定的 url 访问.
I've got a controller that can't be accessed directly, in the traditional RESTful way, but rather only through a particular url.
通常我习惯于在我的控制器规范中使用 get 和 post 来调用控制器操作.有没有办法通过访问特定的 url 来锻炼我的控制器?
Normally I'm used to using get and post in my controller specs to call controller actions. Is there a way that I can exercise my controller by visiting a particular url?
这是我的路线:
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
推荐答案
控制器测试使用四个 HTTP 动词(GET、POST、PUT、DELETE),无论您的控制器是否是 RESTful.所以如果你有一个非 RESTful 路由 (Rails3):
Controller tests use the four HTTP verbs (GET, POST, PUT, DELETE), regardless of whether your controller is RESTful. So if you have a non-RESTful route (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
都会通过,因为路由接受任何动词.
will both pass, since the route accepts any verb.
编辑
我认为您将控制器测试和路由测试混为一谈.在控制器测试中,您要检查操作的逻辑是否正常工作.在路由测试中,您检查 URL 是否转到正确的控制器/操作,以及 params 哈希是否正确生成.
I think you're mixing up controller tests and route tests. In the controller test you want to check that the logic for the action works correctly. In the route test you check that the URL goes to the right controller/action, and that the params hash is generated correctly.
因此要测试您的控制器操作,只需执行以下操作:
So to test your controller action, simply do:
post :create, :provider => "twitter"`
要测试路由,请使用 params_from
(对于 Rspec 1)或 route_to
(对于 Rspec 2):
To test the route, use params_from
(for Rspec 1) or route_to
(for 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
这篇关于测试无法直接访问的 RSpec 控制器操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!