设计+ RSpec:如何验证用户?

时间:2014-01-30 22:35:34

标签: ruby-on-rails rspec devise

我正在使用Devise进行成员身份验证。 我需要测试成员的登录方案。 sign_in(member)不检查身份验证信息 - 它只是在成员中签名,这就是为什么我使用authenticate_member!方法进行身份验证,如Github Issue: How to authenticate the user with warden/devise in a customized way?中所述。

但我得到一个例外ArgumentError: uncaught throw :warden

        #spec/features/member.rb
        FactoryGirl.define do
          factory :member do
            email "john@gmail.com"
            password "12345678"
            firstname "John"
            lastname  "Doe"
            location "United States"
          end
        end

       #spec/controllers/sessions_spec.rb
       it "authenticate member" do

          create(:member)
          @request.env["devise.mapping"] = Devise.mappings[:member]
          @request.env["warden"] = warden

          controller.allow_params_authentication!
          expect(controller.authenticate_member!(:scope => :member, :force => true)).not_to be nil

        end

我还试图设置controller.resource = FactoryGirl.attributes_for(:member)认为资源没有设置但是我得到了异常

NoMethodError: protected method 'resource=' called for #<Devise::SessionsController:0x007ffc4e5bab10>

如何解决此问题?

1 个答案:

答案 0 :(得分:2)

我在Devise上发布了关于这个问题的github问题:Github Issue: RSpec with Devise : How to authenticate a user?

我被建议使用postsessions#create来模拟来自登录表单的POST请求。

以下是另一种解决方案:

   #spec/controllers/sessions_spec.rb
   it "authenticate member" do

     create(:member)
     @request.env["devise.mapping"] = Devise.mappings[:member]
     @request.env["warden"] = warden

     ## Added post request to "create"  
     post :create, :member => FactoryGirl.attributes_for(:member)

     ## Added new expectations 
     expect(controller.member_signed_in?).to be true
     expect(controller.current_member.email).to eq "john@gmail.com"

     ## "session["warden.user.member.key"][0].first" stores the "id" of logged in member
     ## Replace "member" in "session["warden.user.member.key"][0].first" with your 
     ## devise model name. For example: If your devise model name is customer then you  
     ## need to check "session["warden.user.customer.key"][0].first"   
     expect(session["warden.user.member.key"][0].first).to eq member.id

    end

注意: 我本来希望得到一个解释,为什么我之前提到的代码和Devise team {{1}}提供的代码没有解决它应该具有的问题。如果有人找到解释为什么我以前的成员身份验证代码不起作用,请随意发布新答案。