我正在使用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
模型只name
和comment
訪問
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
列表的詳細屬性,這可能會成爲一個大量的工作。或者,如果你有更好的設計模式,請讓我知道
謝謝
如果您使用'create!',該怎麼辦? – apneadiving