Devise Rspec希望响应有一个成功状态代码(2xx),但它是302

时间:2017-02-21 19:33:16

标签: ruby-on-rails ruby rspec devise

我正在使用FactoryGirl创建user,需要company才能成功登录root_url

我根本没有运气用户方法登录。我已经跟踪了this tutorial用户的Devise部分,需要对其进行修改,因为我的用户还需要company与之关联。

我现在已经创建了一个名为Scans的新模型/控制器,它位于Devise的authenticate过滤器之后,并且是我测试失败的第一个过程:

5) ScansController GET #show returns http success
     Failure/Error: expect(response).to have_http_status(:success)
       expected the response to have a success status code (2xx) but it was 302
     # ./spec/controllers/scans_controller_spec.rb:32:in `block (3 levels) in <top (required)>'
     # ./spec/spec_helper.rb:127:in `block (3 levels) in <top (required)>'
     # ./spec/spec_helper.rb:126:in `block (2 levels) in <top (required)>'

目前的规格是:

require 'rails_helper'

RSpec.describe ScansController, type: :controller do

  before(:all) do
    @user = build(:user)
    @company = build(:company)
    @device = build(:device)
    @scan = build(:scan)
  end

  describe "GET #show" do
    it "returns http success" do
      login_with @user
      get :show, :device_id => @device.id, :id => @scan.id
      expect(response).to render_template(:show)
    end
  end

我正在对回复做puts,因为我想知道回复了什么:

ScansController
  GET #show
302
{"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff", "Location"=>"http://test.host/login", "Content-Type"=>"text/html; charset=utf-8"}
#<Rack::BodyProxy:0x007fb52a7407c0>

所以,我正被重定向回我的登录页面,告诉我login_with中的ControllerHelpers方法无法正常工作:

module ControllerHelpers
  def login_with(user = double('user'), scope = :user)
    current_user = "current_#{scope}".to_sym
    if user.nil?
      allow(request.env['warden']).to receive(:authenticate!).and_throw(:warden, {:scope => scope})
      allow(controller).to receive(current_user).and_return(nil)
    else
      allow(request.env['warden']).to receive(:authenticate!).and_return(user)
      allow(controller).to receive(current_user).and_return(user)
    end
  end
end

现在,我的登录功能目前正常工作(手动测试)。 ApplicationController之后触发的第一个控制器是PagesController#home

def home
  if current_user && current_user.company
     verify_subscription
     ....
  else
     redirect_to new_company_path
  end
end

如果verify_subscription失败,用户也会被发送到new_company_path,因此似乎与此问题无关。

基于我的基本rspec功能,我是否正确地假设我甚至没有接近模仿登录?如果没有,我做错了什么?

1 个答案:

答案 0 :(得分:1)

经过多次修补后,我终于通过了测试。我最终在我的用户工厂中创建了一家公司:

after(:build) do |user|
  user.company = create(:company)
end
相关问题