0

valid_attributes在 rspec 控制器规范中,在模型has_one关联时定义方法的正确方法是什么?

*Rails 3.2.12、rspec 2.12、factory_girl_rails 4.2.1*

如果你创建一个包含两个模型 Person 和 Brain 的新 Rails 项目,如下所示:

rails new crowd
cd crowd
rails g scaffold person name:string
rails g scaffold brain weight_kg:float

(并做所有的工作来关联它们),你最终可以得到这些模型:

class Brain < ActiveRecord::Base
  belongs_to :person
  attr_accessible :weight_kg
  attr_accessible :person
  attr_accessible :person_attributes
  accepts_nested_attributes_for :person
end
class Person < ActiveRecord::Base
  has_one :brain
  attr_accessible :name
  attr_accessible :brain
  attr_accessible :brain_attributes

  accepts_nested_attributes_for :brain
  validates :brain, :presence => { :message => "Please give me a brain" }
end

spec/controllers/people_controller_spec.rb 的相关自动生成内容:

describe PeopleController do
  def valid_attributes
    {
        "name" => "A Person",
    }
  end

此时valid_attributes 对Person 无效,因为它缺少Brain。好吧,让我们添加一个。但是怎么做?

错误的:

  def valid_attributes
    {
        "name" => "A Person",
        "brain" => { "weight_kg" => "25" }
    }
  end

^ 生成ActiveRecord::AssociationTypeMismatch: Brain(#86698290) expected, got ActiveSupport::HashWithIndifferentAccess(#84831840)

错误的:

  def valid_attributes
    {
        "name" => "A Person",
        "brain" => Brain.new(:weight_kg => 25)
    }
  end

^ 因为它不会保存。错误将是Expected response to be a <:redirect>, but was <200>expected persisted? to return true, got false以及其他 2 个。

错误:(假设一个有效的规范/工厂/brain.rb)

  def valid_attributes
    {
        "name" => "A Person",
        "brain" => FactoryGirl.build(:brain),
    }
  end

^ 这是错误的,因为这也不会person在创建/更新时保存记录。错误将是Expected response to be a <:redirect>, but was <200>expected persisted? to return true, got false以及其他 2 个。

4

1 回答 1

1
  def valid_attributes
    {
        "name" => "A Person",
        "brain_attributes" => { "weight_kg" => "25" }
    }

或者

  def valid_attributes
    {
        "name" => "A Person",
        "brain_attributes" => FactoryGirl.attributes_for(:brain)
    }
于 2013-02-15T18:32:18.757 回答