我正在尝试在我自己的应用程序中从头开始实现 Railscasts 授权,但是我在自定义匹配器和测试方面遇到了一个简单的问题。我收到错误数量的参数错误,我似乎无法弄清楚原因。
我创建了一个单独的权限模型来保存所有逻辑,并且在这个模型中有一个allow?
方法。这就是所有逻辑的所在。我通过浏览器手动测试它并且它可以工作但是我的单元测试由于参数数量错误而失败
wrong number of arguments (2 for 1)
这是权限模型
class Permission < Struct.new(:user)
def allow?(controller, action)
return true if controller == 'sessions'
return true if controller == 'users' && action.in?(%w[new create])
if user && user.teams.nil?
return true if controller == 'users' && action.in?(%w[new index show edit update])
return true if controller == 'teams' && action.in?(%w[new create index])
return true if controller == 'user_teams' && action.in?(%w[index])
elsif user && !user.teams.nil?
return true if controller == 'users' && action.in?(%w[index show edit update])
return true if controller == 'teams' && action.in?(%w[new create index show])
return true if controller == 'user_teams' && action.in?(%w[index])
return true if controller == 'texts' && action.in?(%w[new create index show])
return true if controller == 'translations' && action.in?(%w[show])
end
end
end
这是位于的自定义匹配器的代码spec/support/matchers/allow.rb
RSpec::Matchers.define :allow do |*args|
match do |permission|
permission.allow?(*args).should be_true
end
failure_message_for_should do |permission|
"expected to have permission for these actions"
end
failure_message_for_should_not do |permission|
"expected to not have permission for these actions"
end
description do
"allow access to the %{*args} actions"
end
end
这是我的应用程序控制器
class ApplicationController < ActionController::Base
before_filter :authorize
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
include SessionsHelper
include UserTeamsHelper
add_flash_types :success, :danger
private
def current_permission
@current_permission ||= Permission.new(current_user)
end
def authorize
if !current_permission.allow?(params[:controller], params[:action])
redirect_to root_url, danger: 'Önce Giriş Yapmalısınız'
end
end
end
这是 Permission 模型的测试
require "spec_helper"
describe Permission do
describe 'as a non user' do
subject { Permission.new(nil) }
it { should allow("sessions", "new") }
end
end
但它不起作用,因为我收到错误数量的参数错误。有人可以指出我测试这些的正确路径吗?
这是我得到的测试失败
Failures:
1) Permission as a non user
Failure/Error: it { should allow("sessions", "new") }
ArgumentError:
wrong number of arguments (2 for 1)
# ./spec/models/permission_spec.rb:6:in `block (3 levels) in <top (required)>'
Finished in 0.07471 seconds
1 example, 1 failure
Failed examples:
rspec ./spec/models/permission_spec.rb:6 # Permission as a non user