我的控制器是這樣的:
before_filter: check_login_status
def check_login_status
send_response(:not_logged_in) unless user.logged_in?
end
我對此的規范是:
it 'returns error unless user is not logged in' do
expect(controller).to receive(:send_response).with(:not_logged_in)
controller.send(:check_login_status)
end
現在我想寫另一個測驗:
it 'checks the login status of user before any action' do
.......
end
我怎樣才能完成第二次測驗?
uj5u.com熱心網友回復:
你不測驗回呼 - 你測驗行為。
回呼是控制器的內部實作細節,并被實作為私有方法(或者至少應該是,如果你做得對的話)。您應該測驗應用程式的行為,而不是它如何完成作業。
為了測驗身份驗證,您需要撰寫一個請求規范,在其中向端點發送一個真實的 HTTP 請求并撰寫有關以下內容的期望:
- 是否回傳了正確的狀態碼?
- 用戶是否被重定向?
- 是否有任何不應該發生的副作用發生?例如正在創建、銷毀或更新的記錄。
- 用戶是否獲得了他們不應該獲得的任何資訊?
一個例子:
require 'spec_helper'
RSpec.describe "Things", type: :request do
describe "POST /things" do
context "when not logged in" do
let(:action) do
post '/things', params: { thing: { foo: 'bar' }}
end
it "does not allow a thing to be created" do
expect{ action }.to_not change(Thing, :count)
end
it "redirects the user to the login page" do
action
expect(response).to redirect_to '/login'
end
# etc
end
end
end
這種測驗可能有些重復和乏味 - 共享示例可以幫助解決這個問題。
或者,您可以正確執行身份驗證系統,以便它實際上引發一個例外,您可以通過禁用rescue_from 來測驗該例外。你很想戳進去的事實實際上可能透露出一種設計的味道。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/406644.html
標籤:
上一篇:如何在collection_select中修復此sort_by在瀏覽器中有效,但在Capybara中回傳“字串與nil的比較失敗”錯誤
