2011-05-05 77 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更多關於應該匹配器。)