检查在devise中用户是否已注销

14

我正在尝试检查在 Rspec 测试中管理员是否已注销。然而,通常的 signed_in? 方法在 rspec 中无法看到,并且不是 RSpec Devise Helpers 的一部分。

我已经实现了类似以下代码:

before (:each) do
        @admin = FactoryGirl.create(:administrator)
        sign_in @admin
      end


      it "should allow the admin to sign out" do
        sign_out @admin
        #@admin.should be_nil
        #@admin.signed_in?.should be_false
        administrator_signed_in?.should be_false
      end

有没有其他方法可以检查管理员的会话并查看他是否真正登录?

4个回答

11

8

1
确实。我刚在一些旧的Ruby代码中发现了subject.current_administrator.should be_nil。在那之前,我对subject一无所知。谢谢。 - Overtone
在我的例子中,应该不是使用administrator作为用户模型,而是使用current_administrator。 - Overtone
1
未定义局部变量或方法 `current_user'...但是 current_administrator 可以工作。奇怪。 - Overtone
3
这只测试设备测试助手方法sign_in和sign_out。如果我想测试网站中的某些内容实际上是如何登录或注销用户的呢?如果我使用Factory创建一个用户,然后使用Capabara能力登录该用户,则无法使用current_user变量。你有什么想法吗? - Rebekah Waterbury
在 RSpec 3 的语法中,使用 expect(subject.current_user).to eq your_expectation - Bruno Buccolo
显示剩余2条评论

8

其实这并不是一个新的答案,但我的声望还不够高以便进行评论...:

  • If you've already overridden subject, the controller is available as controller in controller specs, so:

    expect { ... }.to change { controller.current_user }.to nil
    
  • To check for a specific user, say generated by FactoryGirl, we've had good success with:

    let(:user) do FactoryGirl.create(:client) ; end
    ...
    it 'signs them in' do
        expect { whatever }.to change { controller.current_user }.to user
    end
    
    it 'signs them out' do
        expect { whatever }.to change { controller.current_user }.to nil
    end
    

1
它 "登录和退出用户" do
  user = User.create!(email: "user@example.org", password: "very-secret")
  sign_in user
  expect(controller.current_user).to eq(user)
sign_out user expect(controller.current_user).to be_nil end

您可以参考此链接 devise spec helper link


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接