首页 > 解决方案 > 使用登录设备进行 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

标签: ruby-on-railstestingrspecdevise

解决方案


before(:all)只会运行一次。这就是为什么只有第一次测试通过。

使用before(:each)或干脆before do

此外,应该为每个测试创建用户变量,这意味着它应该在 before 块中声明:

before do
  user = FactoryBot.create(:user)
  login_as(user, :scope => :user)
end

推荐阅读