问题描述
我正在开发一个 Rails 应用程序,它有一个 JSON 格式的 REST API 和版本(根据这个优秀的 Ryan 演员表:http://railscasts.com/episodes/350-rest-api-versioning).
I'm working on a Rails application having a REST API in JSON format and versioned (according to this excellent Ryan's cast: http://railscasts.com/episodes/350-rest-api-versioning).
例如,有一个规范/请求规范:
For instance, there is a spec/requests spec:
require 'spec_helper'
describe "My Friends" do
describe "GET /my/friends.json" do
it "should get my_friends_path" do
get v1_my_friends_path, {}, {'HTTP_ACCEPT' => 'application/vnd.myapp+json; level=1'}
response.status.should be(401)
end
end
end
而且效果很好.但是(保持这个例子)我们如何编写路由规范?例如,此规范不正确:
And it works well. But (keeping this example) how can we write the routing spec? For instance this spec isn't correct:
require 'spec_helper'
describe "friends routing" do
it "routes to #index" do
get("/my/friends.json", nil, {'HTTP_ACCEPT' => 'application/vnd.myapp+json; level=1'}).
should route_to({ action: "index",
controller: "api/v1/private/my/friends",
format: "json" })
end
end
我尝试了不同的方式(例如request.headers['Accept']
和@request.headers['Accept']
,其中request
code> 未定义且 @request
为零);我真的不知道该怎么做.
I tried different ways (such as request.headers['Accept']
and @request.headers['Accept']
, where request
is undefined and @request
is nil); I really don't see how to do.
我使用的是 Ruby 1.9.3、Rails 3.2.6 和 rspec-rails 2.11.0.谢谢.
I'm on Ruby 1.9.3, Rails 3.2.6 and rspec-rails 2.11.0. Thanks.
推荐答案
通过结合 Cristophe 和 Piotr 的答案中的想法,我想出了一个对我有用的解决方案.我使用的是 rspec 和 rails 3.0.
By combining the ideas from Cristophe's and Piotr's answers, I came up with a solution that worked for me. I'm using rspec and rails 3.0.
it 'should route like i want it to' do
Rack::MockRequest::DEFAULT_ENV["HTTP_ACCEPT"] = "*/*"
{get: "/foo/bar"}.
should route_to(
controller: 'foo',
action: 'bar',
)
Rack::MockRequest::DEFAULT_ENV.delete "HTTP_ACCEPT"
end
这篇关于Rspec:在路由规范中添加一些标头请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!