RSpec & 设计身份验证不起作用

RSpec & Devise authentication don't works

我在使用 RSpec 和 Devise

时遇到了非常奇怪的问题
  describe 'GET edit:/id' do 
    before do 
      @job = FactoryGirl.create(:job)
      get(:edit, id: @job.id)
    end

    context 'as not authorized' do
      before { logout(:user) }
      it 'redirects to login page' do
        expect(response).to redirect_to new_user_session_path
      end
    end

    #it '' do end << works if i uncomment this line

     context 'as authorized' do
      before { login_as(user) }
      it 'renders edit tempalte' do
        expect(response).to render_template :edit
       # Here I get response.status 302. It must be 200, controller thinks that user is not authorized.
       # But if add empty 'it' keyword, everything works fine
      end
    end
  end

控制器之前的过滤器

before_filter :authenticate_user!, except: [:index, :show]

我不知道为什么如果添加空 'it' 关键字一切正常。

但是,我知道为什么 context 'as authorized' 不能正常工作。 我试过了,代码工作正常。

规范文件。我换了2行。请看评论。

# spec/controllers/jobs_controller.rb
require 'rails_helper'

RSpec.describe JobsController, :type => :controller do
  describe 'GET edit:/id' do
    context 'as not authorized' do
      before do
        @job = FactoryGirl.create(:job)
        get(:edit, id: @job.id)
      end
      it 'redirects to login page' do
        expect(response).to redirect_to new_user_session_path
      end
    end

    context 'as authorized' do
      before do
        user = FactoryGirl.create(:user) # add here
        sign_in(user)  # change
        @job = FactoryGirl.create(:job)
        get(:edit, id: @job.id)
      end

      it 'renders edit tempalte' do
        expect(response).to render_template :edit
      end
    end
  end
end

将 Devise 的测试助手添加到 rails_helper.rb

# spec/rails_helper.rb
# Add this line to provide Devise's test helpers
# Ref: https://github.com/plataformatec/devise#test-helpers
config.include Devise::TestHelpers, type: :controller

出厂文件。

# spec/factories/users.rb
FactoryGirl.define do
  factory :user do
    email 'test@email.com'
    password 'password'
  end
end

运行 成功!!

rspec spec/controllers/jobs_controller_spec.rb
..

Finished in 0.09395 seconds (files took 2.31 seconds to load)
2 examples, 0 failures