【发布时间】:2017-07-11 14:35:01
【问题描述】:
我有一个 user,我正在使用 FactoryGirl 创建它,它需要有一个 company 才能成功登录到我的 root_url。
我没有任何运气来存根用户登录方法。对于用户的 Devise 部分,我已关注 this tutorial 并需要对其进行一些修改,因为我的用户还需要将 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>
所以,我被重定向回我的登录页面,这告诉我ControllerHelpers 中的login_with 方法无法正常工作:
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 功能,我是否正确地假设我什至没有接近模仿登录?如果没有,我做错了什么?
【问题讨论】:
-
还有,
login_with方法用在哪里? -
@zetetic 为您更新了 rspec 方法...
login_with在那里。
标签: ruby-on-rails ruby rspec devise