ruby-on-rails - 使用登录设备进行 Rspec 测试只需一次
问题描述
我正在尝试使用 devise 和 rspec 测试一些视图。在这个测试中,第一个通过了。第二个是重定向到登录页面。
login_as 只是在第一个测试中工作。如果我添加 3 个测试,最后一个失败,前 2 个通过。如果我更改:all
为:each
第一个失败并且第二个通过
require 'rails_helper'
RSpec.describe StoresController, type: :controller do
context "with valid params" do
user = FactoryBot.build(:user)
before(:all) do
login_as(user, :scope => :user)
end
it "renders the index template" do
get :index
expect(response).to render_template("index")
end
it "creates a new store" do
get :new
expect(response).to render_template("new")
end
end
end
解决方案
before(:all)
只会运行一次。这就是为什么只有第一次测试通过。
使用before(:each)
或干脆before do
此外,应该为每个测试创建用户变量,这意味着它应该在 before 块中声明:
before do
user = FactoryBot.create(:user)
login_as(user, :scope => :user)
end
推荐阅读
- python - 在 conda-build 配方中排除特定的 Python 版本
- jakarta-ee - 在 github 操作中针对 Chrome 无头运行 Arquillian 测试
- windows - 受密码保护的 zip 与加密的 zip 文件是否不同?
- mitmproxy - 为多个上游 ip 生成证书
- javascript - 如何使用 Javascript 在 html 中显示图像
- python - 我如何连接一列 QTableWidget
- reactjs - React daterangepicker - 移动友好
- c# - 如果字符串列表具有特定字符串,则匹配 c# 尝试过 .Any
- java - Selenium:- 无法在文本框中写入
- flutter - Flutter Performance 的内存使用窗口不显示任何内容