【发布时间】:2016-06-13 14:40:44
【问题描述】:
当我在我的一个项目规范类上运行 rspec wit pundit 1.0 版 时,我遇到了多个以前从未见过的错误。但是,当我切换到以前版本的 pundit (0.3) 时,一切正常。
到目前为止,我注意到的是新版本的 pundit @error 在 create 函数中没有正确分配(而不是错误类,我从错误类中得到一个错误消息字符串)。
class ErrorsController < ApplicationController
before_action :set_execution_environment
def authorize!
authorize(@error || @errors)
end
private :authorize!
def create
@error = Error.new(error_params)
authorize!
end
def error_params
params[:error].permit(:message, :submission_id).merge(execution_environment_id: @execution_environment.id)
end
private :error_params
在规格/工厂中:
FactoryGirl.define do
factory :error, class: Error do
association :execution_environment, factory: :ruby
message "exercise.rb:4:in `<main>': undefined local variable or method `foo' for main:Object (NameError)"
end
end
在规范/控制器/error_controller.rb 中:
describe 'POST #create' do
context 'with a valid error' do
let(:request) { proc { post :create, execution_environment_id: FactoryGirl.build(:error).execution_environment.id, error: FactoryGirl.attributes_for(:error), format: :json } }
context 'when a hint can be matched' do
let(:hint) { FactoryGirl.build(:ruby_syntax_error).message }
before(:each) do
expect_any_instance_of(Whistleblower).to receive(:generate_hint).and_return(hint)
request.call
end
expect_assigns(execution_environment: :execution_environment)
it 'does not create the error' do
allow_any_instance_of(Whistleblower).to receive(:generate_hint).and_return(hint)
expect { request.call }.not_to change(Error, :count)
end
it 'returns the hint' do
expect(response.body).to eq({hint: hint}.to_json)
end
expect_json
expect_status(200)
end
context 'when no hint can be matched' do
before(:each) do
expect_any_instance_of(Whistleblower).to receive(:generate_hint).and_return(nil)
request.call
end
expect_assigns(execution_environment: :execution_environment)
it 'creates the error' do
allow_any_instance_of(Whistleblower).to receive(:generate_hint)
expect { request.call }.to change(Error, :count).by(1)
end
expect_json
expect_status(201)
end
end
我收到错误消息
Pundit::NotDefinedError: 无法为
#<Pundit::Error: {"message"=>"exercise.rb:4:in' 找到策略Pundit::ErrorPolicy:未定义 局部变量或方法foo' for main:Object (NameError)", "execution_environment_id"=>1}>
因为没有正确创建错误类。之后,错误类中的每个测试都失败了。
我的政策:
class AdminOrAuthorPolicy < ApplicationPolicy
[:create?, :index?, :new?].each do |action|
define_method(action) { @user.internal_user? }
end
[:destroy?, :edit?, :show?, :update?].each do |action|
define_method(action) { admin? || author? }
end
end
class ErrorPolicy < AdminOrAuthorPolicy
def author?
@user == @record.execution_environment.author
end
end
我对任何其他课程都没有这样的问题。
【问题讨论】:
标签: ruby-on-rails ruby rspec pundit