我正在尝试为我正在构建的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
但我想知道这是否是“正确的”方式。
具体来说,the request spec scenarios on relishapp.com显示使用params
选项哈希作为POST请求的一部分,我想知道此选项哈希是否也适用于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"} }
...
答案 0 :(得分:0)
您不需要在请求方法中指定整个网址。 Rspec提供了一种较短的方法,如下所述
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 :edit, { id: company.id } # In this hash you can send any paramter, this will end up becoming your params for the request
expect(response).to redirect_to(new_user_session_path)
...
end
end
end
也可以通过以下方式重写上面提到的(post,new,index)请求 -
get :index
expect(response).to redirect_to(new_user_session_path)
post :create
expect(response).to redirect_to(new_user_session_path)
get :new
expect(response).to redirect_to(new_user_session_path)