rspec控制器测试中嵌套关联的正确格式是什么?

时间:2013-02-15 18:32:19

标签: ruby-on-rails rspec associations

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

* Rails 3.2.12,rspec 2.12,factory_girl_rails 4.2.1 *

如果您使用两个模型创建一个新的Rails项目,Person和Brain,就像这样:

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

此时,对于Person,valid_attributes无效,因为它缺少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个。

错误:(假设有效的spec / factories / 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个。

1 个答案:

答案 0 :(得分:1)

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

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