[英]Ruby on Rails allow mass assignment for an RSpec test
我正在用RSpec測試我的Rails應用程序,但后來我遇到了一個問題。 我想要一個一致的數據庫,因此我強制要求某些列不能為空。
我有一個評論模型,評論可能是另一個評論的答案。 Morevoer評論的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
然后我創建了一個只有name
和comment
可訪問的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
列表的可能性。 或者如果你有更好的設計模式,請告訴我
謝謝
我在搜索同一問題的解決方案時遇到了這個問題。 我知道它已經很老了,但是為了什么值得我挖掘代碼並決定以這種方式解決問題:
before :each do
ActiveModel::MassAssignmentSecurity::WhiteList.any_instance.stub(:deny?).and_return(false)
end
也許這對於卷入這里的其他人來說會派上用場。
只需使用:
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
在測試過程中,我基本上使用了這種變體(以及其他一些調整)。
(但法比奧的答案更清晰 - 這是工廠的事情之一,制造東西 - 不僅僅是屬性的持有者:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.