如何使用RSpec中的Devise登录多个用户?

时间:2016-01-30 22:06:01

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

在我的规范中,我有before :each

  before :each do
    @user1 = create(:user, gender: 0)
    @user2 = create(:user)
    @membership1 = create(:membership, member: nil, family_tree: @user1.family_tree, inviter: @user1, invited: @user2, relation: "sister", relative_type: 1)
    @membership2 = create(:membership, member: nil, family_tree: @user2.family_tree, inviter: @user2, invited: @user1, relation: "brother", relative_type: 1)
    @connection = create(:connection, inviter_membership: @membership1, invited_membership: @membership2, inviter_user: @user1, invited_user: @user2, request_status: 1)
    sign_in @user1
  end
然后我接受了这个失败的测试:

  it "should NOT delete the inviter_membership record" do
    expect {
      delete :destroy, id: @user1
    }.not_to change(Membership,:count)
  end

这是我得到的错误:

RSpec::Expectations::ExpectationNotMetError: expected #count not to have changed, but did change from 2 to 1

但是,一旦我执行此操作:sign_in @user2,该测试就会通过。但是因为我不再登录@user1其他测试失败了。我不确定如何同时在两个用户中签名。

最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

实际上,我想通了。

我所要做的就是将sign_in @user1留在before :each,然后在单独的测试中,我只需sign_in @user2

所以测试现在看起来像这样:

  it "should NOT delete the inviter_membership record" do
    sign_in @user2
    expect {
      delete :destroy, id: @user1
    }.not_to change(Membership,:count)
  end

我仍然不明白为什么在这种情况下它需要第二个用户登录....但至少它不再失败。

也许有一些验证在销毁或更新时失败了。