我正在尝试为我正在构建的Rails应用编写请求规范,但是文档很少(或者我还没有找到合适的文档)。
我有一个companies
资源,其中包含大多数常用的API端点:
# Routes -------------------------------------------------------------------
# companies GET /companies(.:format) companies#index
# POST /companies(.:format) companies#create
# new_company GET /companies/new(.:format) companies#new
# edit_company GET /companies/:id/edit(.:format) companies#edit
# company GET /companies/:id(.:format) companies#show
# DELETE /companies/:id(.:format) companies#destroy
# PATCH /companies/:id(.:format) companies#update
我希望我的规范指出,如果您在未登录时遇到这些端点,它们会将您重定向到登录页面。对于前三个端点(没有:id
参数的端点),这很简单:
RSpec.describe 'Companies Endpoints', type: :request do
context 'with anonymous user' do
it 'always redirects to sign-in page' do
get '/companies'
expect(response).to redirect_to(new_user_session_path)
post '/companies'
expect(response).to redirect_to(new_user_session_path)
get '/companies/new'
expect(response).to redirect_to(new_user_session_path)
end
end
当端点包含一个URL参数(get '/companies/:id/edit'
)时,请求的语法是什么?这是我到目前为止提出的语法:
RSpec.describe 'Companies Endpoints', type: :request do
let :company { FactoryGirl.create(:company) } # NOTE: this is new
context 'with anonymous user' do
it 'always redirects to sign-in page' do
...
get "/companies/#{company.id}/edit" # `company` is from the factory above
expect(response).to redirect_to(new_user_session_path)
...
end
end
但我在想这是不是“正确”的路。
具体来说,www.example.com上的请求规范场景relishapp.com显示了作为POST请求的一部分使用params
选项哈希,我想知道此选项哈希是否也适用于URL参数?
RSpec.describe "Widget management", :type => :request do
it "creates a Widget and redirects to the Widget's page" do
post "/widgets", :params => { :widget => {:name => "My Widget"} }
...
2条答案
按热度按时间p1iqtdky1#
你不需要在request方法中指定整个URL,Rspec提供了一个更短的方法,如下所述
此外,而不是(后,新,索引)的要求,你上面提到的可以重写以下方式-
hvvq6cgz2#
我一直在寻找答案,使我能够在控制器中使用rails
request.query_parameters
和request.request_parameters
,并使用rspecrequest
规范对其进行适当的测试。要使其真正工作,您需要根据rails解析参数的方式指定内容类型和长度:https://apidock.com/rails/ActionController/ParamsParser/parse_formatted_parameters