2011-05-05 71 views
5

也许这不是需要测试的东西,但我正在学习,所以我不认为它是错误的测试到最大值。大规模分配测试

我有几个测试,除了一个产生预期的结果。我发现了一种解决方法,但我想知道正确的方法是什么。

当我在rails控制台中测试保存时,它不保存params哈希中的admin字段,这正是我所期望的。当我用工厂构建并保存时,验证会相应地通过/失败。当我测试质量分配保护时,测试失败(因为它设置管理员字段,当我预计它不会)

任何想法,建议或疑虑?

感谢

型号:

class User ... 
    #id, name, email, admin(int) 
    attr_accesible :name, email 
    ... 
end 

user_spec

it "should not have an admin after a mass save" do 
    user = Factory.build(:user) 
    user.save 
    user.admin.should be_nil #its not nil, its 0  
end 

工厂

Factory.define :user do |f| 
    f.name "rec_acro" 
    f.email "[email protected]" 
    f.admin 0 
end 

回答

13

您可以使用Shoulda在rspec的顶部得到一个简洁的质量分配规格:

describe User do 
    it { should_not allow_mass_assignment_of(:admin) } 
end 
+0

你并不需要使用RSpec的使用早该。 – 2011-05-05 03:30:15

+5

没错,但由于OP已经在使用rspec,我只是指出它们可以一起使用。 – 2011-05-05 04:01:18

+1

那么你认为只有那些会阅读这个问题和答案寻求帮助的人是OP吗?我正在为其他人注意到它。 – 2011-05-05 15:25:08

2

工厂女孩(理所当然)不使用质量分配来生成对象。从工厂取出生成的用户对象,然后尝试对其进行批量分配,尽管只有admin参数。

3

FactoryGirl将采用Factory定义中的每个属性并单独设置它。所以,你的实际测试不测试质量分配

从FactoryGirl代码(build.rb):(见this如果你有兴趣更多的代码读取的FactoryGirl宝石)

def set(attribute, value) 
    @instance.send(:"#{attribute}=", value) 
    end 

作为另一个建议,您可以使用Shoulda来使用allow_mass_assignment_of匹配器。它基本上是这样的:

it "allows mass assignment of :title" do 
    accessible = Post.accessible_attributes.include?('title') || 
      !Post.protected_attributes.include?('title') 
    accessible.should be_true 
end 

Here's a little更多关于应该匹配器。)