簡體   English   中英

Ruby on Rails允許RSpec測試的質量分配

[英]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

然后我創建了一個只有namecomment可訪問的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM