我很难弄清楚如何使用rspec和shoulda_matchers测试强大的参数。
无论我尝试了什么,我总是收到以下消息:RSpec::Expectations::ExpectationNotMetError: Expected POST #create to restrict parameters on :language_name to :name,
but it did not restrict any parameters.
这是我的控制者:
class LanguageNamesController < CrudController
inherit_resources
actions :all, :except => [:show]
private
def language_name_params
params.require(:language_name).permit(:name)
end
end
这是测试:
require 'rails_helper'
RSpec.describe LanguageNamesController, type: :controller do
describe "parameters" do
it do
lm_params = {
language_name: {
name: 'John'
}
}
expect(subject).to permit(:name).for(:create, params: { params: lm_params }).on(:language_name)
end
end
end
此外,我已经尝试过并得到相同的结果:
it do
subject.params = ActionController::Parameters.new(language_name: {foo: 'bar', name: 'baz'})
expect(subject).to permit(:name).for(:create).on(:language_name)
end
如果我这样尝试,我会得到ArgumentError: unknown keyword: language_name
:
it do
lm_params = {
language_name: {
name: 'John'
}
}
expect(subject).to permit(:name).for(:create, params: lm_params).on(:language_name)
end
我正在使用:
有人知道如何解决这个问题吗?
谢谢!
这是我的测试方法:
it do
faker_name = Faker::Name.name
params = {
language_name: {name: faker_name, other_attribute: "other value"},
extra: {extra: 1}
}
get :index, params: params
expect(subject.send(:language_name_params)).to eq({"name"=> faker_name})
end
答案 0 :(得分:1)
您不需要创建lm_params
。匹配者应该为您模拟params对象。
如果您只需要测试权限,则可以执行should permit(:name).for(:create)
如果您需要检查允许的参数上的值:should permit(:name).for(:create, params: {name: 'John'})
编辑:另一个好的文档来源是rubydoc for shoulda matchers。