gpt4 book ai didi

ruby-on-rails - 轨attr_accessible rspec的检查

转载 作者:行者123 更新时间:2023-12-04 06:09:54 24 4
gpt4 key购买 nike

当我想测试属性是否为/时 无障碍 使用 RSpec 我就是这样做的

class Foo
attr_accesible :something_else
end

describe Foo do
it('author should not be accessible') {lambda{described_class.new(:author=>true)}.should raise_error ActiveModel::MassAssignmentSecurity::Error}
it('something_else should be accessible'){lambda{described_class.new(:something_else=>true)}.should_not raise_error ActiveModel::MassAssignmentSecurity::Error}
end

有没有更好的方法呢?

...谢谢

最佳答案

This is the way attribute accessibility tests are done in the Rails Tutorial ,我觉得还不错。因此,在您的情况下,可以稍微修改测试代码,如下所示:

describe Foo do
describe "accessible attributes" do
it "should not allow access to author" do
expect do
Foo.new(author: true)
end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
end

it "should allow access to something_else" do
expect do
Foo.new(something_else: true)
end.to_not raise_error(ActiveModel::MassAssignmentSecurity::Error)
end
end
end
如果这不是您想要的,当您询问是否有“更好的方法”时,您能否让我们更好地了解您所追求的解决方案?
编辑
您可能对 Shoulda ActiveModel matchers 感兴趣,这会将代码清理为每个测试仅一行。就像是:
it { should_not allow_mass_assignment_of(:author) }
it { should allow_mass_assignment_of(:something_else) }

关于ruby-on-rails - 轨attr_accessible rspec的检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11775084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com