【发布时间】:2015-08-28 18:55:13
【问题描述】:
我正在尝试验证 current_user 的组织是否与他们尝试查看的组织匹配。
这是未通过此测试的控制器部分(@organization 已在早期方法中定义):
if current_user.organization != @organization
redirect_to root_path, notice: "Not authorized to edit this organization"
end
这是失败的测试:
require 'rails_helper'
RSpec.describe Admin::PagesController, :type => :controller do
describe 'GET #home' do
login_user
before do
@organization = FactoryGirl.create(:organization)
end
context "valid params" do
it "renders the home template and returns http 200" do
get :home, name: @organization.name
expect(response).to render_template("home")
expect(response.status).to eq(200)
end
end
end
这是我的工厂:
factory :user do
email { Faker::Internet.email }
organization_id 1
password "foobarfoobar"
password_confirmation { |u| u.password }
end
...这里是 login_user 被定义的地方:
module ControllerMacros
def login_user
@request.env["devise.mapping"] = Devise.mappings[:user]
user = FactoryGirl.create(:user)
sign_in user
end
end
堆栈跟踪:
1) Admin::PagesController GET #home valid params renders the home template and returns http 200
Failure/Error: it "renders the home template and returns http 200" do
expecting <"home"> but rendering with <[]>
# ./spec/controllers/admin/pages_controller_spec.rb:15:in `block (4 levels) in <top (required)>'
但是:
[2] pry(#<RSpec::ExampleGroups::AdminPagesController::GETHome::ValidParams>)> subject.current_user.organization == @organization
=> true
不确定这里出了什么问题,看起来很标准。有什么想法吗?
【问题讨论】:
-
错误是什么?请发布堆栈跟踪。
-
使用堆栈跟踪更新
-
当您在 before 块中创建组织时,您必须将用户附加到该组织。比如使用 oraganization_id = @organization.id 创建用户
-
已经附加了...?默认情况下,我有用户的组织 ID 等于 1。
-
另外,您的 login_user 方法会创建一个新用户,然后登录该用户。不知何故,您需要指定组织和用户之间的关系
标签: ruby-on-rails ruby ruby-on-rails-4 rspec devise