给定一个简单的用户模型,在带有名称,电子邮件和管理员布尔值的Rails 4中,使用RSpec测试批量分配的最佳方法是什么?
这是UsersController:
def create
@user = User.new user_params
...snip
end
private
def user_params
params.require(:user).permit(:name, :email)
end
和测试这两个不同的尝试:
在user_spec.rb中
describe "accessible attributes" do
describe "should not allow access to admin" do
before do
@user.admin = "1"
@user.save
end
it { should_not be_admin }
end
end
或者在users_controller_spec.rb中
it 'should only allow name and email to be set' do
@controller.user_params.keys.should eq(['name', 'email')
end
两者都没有工作 - 前者只是创建一个admin设置为true的用户(测试失败) - 可能会绕过strong_parameters . 后者有效,但前提是user_params方法不是私有的 . (官方文档建议将其设置为私有 . 注意 - 在user_spec中查看MassAssignment错误也不起作用(不会引发错误) .
注意 - 实际上在视图中将用户设置为admin正常工作 - admin属性被过滤掉并且一切都很开心,但是我们真的希望在测试中看到它正常工作 .
另一个建议是使用带有user_spec.rb的shoulda-matchers gem:
describe User do
...
it { should_not allow_mass_assignment_of(:admin) }
...
end
(这也不起作用),给出:
Failure/Error: it { should_not allow_mass_assignment_of(:admin) }
NoMethodError:
undefined method `active_authorizer' for #<Class:0x007f93c9840648>
(我认为这个错误是因为事实上,应用匹配器还不兼容Rails 4) .
提前致谢!
1 回答
为了测试质量分配,您应该模拟来自控制器的传递参数 .
https://github.com/rails/strong_parameters#use-outside-of-controllers