2011-09-17 33 views
3

我正在使用RSpec測試我的Rails應用程序,但後來遇到了問題。我想要一個一致的數據庫,因此我強加了一些約束,某些列不能爲空。Ruby on Rails允許RSpec測試的質量分配

我有一個評論模型和評論可能是對另一個評論的答案。更多評論有一個IP地址不應該爲空。這是遷移:

create_table :comments do |t| 
    t.string :name, :limit => 20, :null => false 
    t.string :comment, :limit => 8192, :null => false 
    t.string :ip, :null => false 
    t.integer :answer_to_comment_id 
end 

然後,我創建了一個Comment模型只namecomment訪問

class Comment < ActiveRecord::Base 
    attr_accessible :name, :comment 

    belongs_to :answer_to, :class_name => "Comment", 
         :foreign_key => "answer_to_comment_id" 

    has_many :answers, :class_name => "Comment", 
        :foreign_key => "answer_to_comment_id", 
        :dependent => :destroy 
end 

factories.rb看起來是這樣的:

Factory.define :comment do |comment| 
    comment.name "test" 
    comment.comment "test" 
    comment.ip  "0.0.0.0" 
end 

現在我有以下問題在RSpec測試中comment_spec.rb

describe "some test" do 
    before(:each) do 
    @answer = @comment.answers.create(Factory.attributes_for(:comment)) 
    end 
end 

這將失敗,因爲:ip不在attr_accessible列表中,因此ActiveRecord無法在數據庫中創建記錄。我可以將:ip添加到列表中,但由於批量分配,這可能會導致一些安全問題。我也可以手動添加的:ip,但如果有像ip

所以我找了可能繞過attr_accessible列表的詳細屬性,這可能會成爲一個大量的工作。或者,如果你有更好的設計模式,請讓我知道

謝謝

+0

如果您使用'create!',該怎麼辦? – apneadiving

回答

1

只需使用:

describe "some test" do 
    before(:each) do 
    @answer = @comment.answers << Factory(:comment) 
    end 
end 

,或者如果你需要一個以上的評論,說n

describe "some test" do 
    before(:each) do 
    @answer = @comment.answers = FactoryGirl.create_list(:comment, n) 
    end 
end 
+0

我發現'@ comment.answers <<'方法返回一個數組,因此這個解決方案適用於我: @ comment.answers <<(@answer = Factory.build(:comment)) 再次感謝您的幫助 – k13n

0

我在測試過程中基本上使用了this的變體(以及其他一些調整)。

(但法比奧的答案是清潔 - 這是的東西工廠都是爲一體,使事情 - 不僅僅是屬性:)

2

我碰到這個問題跑,而尋找解決的辦法,以同樣的持有人問題。我知道這是很老了,但是這是非常值得我通過代碼挖出,並決定要解決的問題是這樣的:

before :each do 
    ActiveModel::MassAssignmentSecurity::WhiteList.any_instance.stub(:deny?).and_return(false) 
end 

這或許能派上用場別人誰在這裏捲起。