我很难弄清楚如何使用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
我正在使用:
- ruby 2.5.1
- 轨道5.1.6
- 是否匹配3.1.2
有人知道如何解决这个问题吗?
谢谢!
这是我测试它的变通方法:
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
您不需要创建lm_params
。Shoulda matchers将为您模拟params对象。
如果你只需要测试权限,你可以做should permit(:name).for(:create)
如果您需要检查允许参数的值:should permit(:name).for(:create, params: {name: 'John'})
文档中有strong_parameters_matcher.rb 的好例子
编辑:另一个很好的文档来源是should匹配器的rubydoc。