检查用户是否已在设计中注销

时间:2012-06-22 15:33:41

标签: ruby-on-rails ruby authentication rspec devise

我正在尝试检查管理员是否在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 个答案:

答案 0 :(得分:8)

我认为这真的是你需要的How To: Test controllers with Rails 3 and 4 (and RSpec)

只需查看current_user即可。它应该是nil

添加。好的做法是使用像这样的语法

-> { sign_out @admin }.should change { current_user }.from(@admin).to(nil)

答案 1 :(得分:8)

it "should have a current_user" do
  subject.current_user.should_not be_nil
end

找到https://github.com/plataformatec/devise/wiki/How-To:-Controllers-and-Views-tests-with-Rails-3-%28and-rspec%29

答案 2 :(得分:4)

确实不是一个新的答案,但我的代表不够评论......:

  • 如果您已覆盖subject,则控制器在控制器规范中可用controller,因此:

    expect { ... }.to change { controller.current_user }.to nil
    
  • 为了检查特定用户,比如FactoryGirl生成的,我们取得了很好的成功:

    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
    

答案 3 :(得分:-1)

it "signs user in and out" 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

相关问题