簡體   English   中英

在Rails集成測試/ RSpec請求規范中指定URL參數

[英]Specify URL parameters in Rails integration test / RSpec request spec

我正在嘗試為我正在構建的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

但我想知道這是否是“正確”的方法。

具體來說, 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"} }
    ...

您無需在請求方法中指定整個URL。 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

同樣,您可以通過以下方式重寫您上面提到的(發布,新建,索引)請求:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM