我很难弄清楚如何测试这个帮助器,因为我的测试用例中没有定义current_group
,我不知道如何将其存根。
module Admin
module EmployeesHelper
def upload_access
policy(current_group).can_bulk_create_employees?
end
def dashboard_params
download_employee_url = upload_access ?
download_admin_group_employees_import_csv_index_path(current_group) : nil
upload_employee_url = upload_access ?
admin_group_employees_import_csv_index_path(current_group) : nil
make_hash(upload_employee_url, download_employee_url)
end
private
def make_hash(upload_url, download_url)
{
employees: @employees,
addEmployeeUrl: new_admin_group_employee_path(current_group),
terminated_employees: @terminated_employees,
new_employees: @new_employees,
test_employees: @test_employees,
group_id: current_group.id,
downloadEmployeeUrl: download_url,
uploadEmployeeUrl: upload_url
}
end
end
end
这是我的测试的样子,但由于未定义current_group
而失败。
require 'rails_helper'
describe Admin::EmployeesHelper do
let!(:group) { create(:group) }
before do
# This stub doesn't work because helper doesn't implement current_group
allow(helper).to receive(:current_group).and_return(group)
end
it 'returns correct dashboard props' do
allow(helper).to receive(:upload_access).and_return(true)
props = helper.dashboard_params
expect(props).values_at(:downloadEmployeeUrl, :uploadEmployeeUrl).should_not include(nil)
end
end
答案 0 :(得分:0)
如果问题仅出现在current_group
方法中,则可以在虚拟类中包含此帮助程序。像这样:
let(:klass) {
Class.new do
include Admin::EmployeesHelper
def current_group
nil
end
end
}
let(:instance) { klass.new }
before do
allow(instance).to receive(:current_group).and_return('whatever') # test-specific group
end
it 'returns correct dashboard props' do
allow(instance).to receive(:upload_access).and_return(true)
props = instance.dashboard_params
expect(props).values_at(:downloadEmployeeUrl, :uploadEmployeeUrl).should_not include(nil)
end
虽然我预见到你也必须为网址助手提供一些东西。并设置那些实例变量。总而言之,它可能不值得麻烦。
答案 1 :(得分:0)
我最终重构了帮助程序而不是current_group
作为参数。