[英]Rspec test fails due to to redirection to a page for loggin in (Rails + Devise + Cancancan)
我正在為 Rails 中的控制器編寫測試:
require 'rails_helper'
RSpec.describe GoodsController, type: :controller do
DatabaseCleaner.clean
user = User.create(password: "12345678")
user.save!
describe "GET index" do
it "renders the index template" do
sign_in user
get "index"
expect(response).to render_template("index")
end
end
DatabaseCleaner.clean
end
GoodsController
有我想測試的這個index
操作:
def index
if params[:category_id] == nil
@goods = Good.all
else
@goods = Good.where(category_id: params[:category_id])
end
end
當我運行測試時,我收到此錯誤:
1) GoodsController GET index renders the index template
Failure/Error: expect(response).to render_template("index")
expecting <"index"> but was a redirect to <http://test.host/users/sign_in>
# ./spec/controllers/goods_controller_spec.rb:12:in `block (3 levels) in <top (required)>'
根據 SO 中的其他答案,我已經添加了sign_in user
行,但沒有幫助。 它仍然重定向到日志記錄頁面。 我該如何解決?
運行示例(又名測試)時,rspec 不使用您創建的user
。 它只是塊內的一個變量,沒有任何用處。
在處理設備/工廠時,您應該在before
、 let
或內部測試本身( it
塊)中創建它們。
describe "GET index" do
let(:user) { User.create(password: "12345678") }
it "renders the index template" do
# OR, create it here before sign_in
sign_in user
get "index"
expect(response).to render_template("index")
end
end
不確定您是否使用factory_bot ,但您應該查看它。 通常DatabaseCleaner
設置在rails_helper
,查看此SO帖子了解更多詳細信息。
如果您要進行多個需要用戶登錄的測試,您還可以將 sign_in 包裝在一個 before 鈎子中。
describe "GET index" do
let(:user) { User.create(password: "12345678") }
before do
sign_in user
end
it "renders the index template" do
get "index"
expect(response).to render_template("index")
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.