1

嗨,我在运行规范文件时遇到了这个问题。这是修复模型:

class Reparator < User
  include Mongoid::Document
  include Mongoid::Timestamps
  field :private_reparator, :type => Boolean, :default => true
  field :brand_name, :type => String
  field :year_of_experience, :type => Integer, :default => 1

  has_many :reparations
  has_many :skills

  validates_presence_of :skills, :year_of_experience
  validates :year_of_experience, :numericality => {:greater_than_or_equal_to => 0}
end

这是技能模型:

class Skill
  include Mongoid::Document

  field :name, :type => String

  belongs_to :reparator

  validates_presence_of :name
  validates_uniqueness_of :name

end

这是控制器:

class ReparatorsController < ApplicationController
  respond_to :json

  def index
    @reparators = Reparator.all
    respond_with @reparators
  end

  def show
    @reparator = Reparator.find(params[:id])
    respond_with @reparator
  end

  def create
    @reparator = Reparator.new(params[:reparator])
    @reparator.skills = params[:skills]
    if @reparator.save
      respond_with @reparator
    else
      respond_with @reparator.errors
    end
  end

  def update
    @reparator = Reparator.find(params[:id])

    if @reparator.update_attributes(params[:reparator])
      respond_with @reparator
    else
      respond_with @reparator.errors
    end
  end

  def destroy
    @reparator = Reparator.find(params[:id])
    @reparator.destroy
    respond_with "Correctly destroyed"
  end

end

这是此控制器的规范文件(我将只放置未通过的测试):

it "Should create an reparator" do
      valid_skills = [FactoryGirl.create(:skill).id, FactoryGirl.create(:skill).id]
      valid_attributes = {:name => "Vianello",
                          :email => "maremma@gmail.com",
                          :address => "viale ciccio",
                          :private_reparator => true
                          }
      post :create, :reparator => valid_attributes, :skills => valid_skills
      assigns(:reparator).should be_a Reparator
      assigns(:reparator).should be_persisted
    end

这是技能工厂女孩:

FactoryGirl.define do
  factory :skill do
    sequence(:name) {|n| "skill#{n}"}
  end
end
4

2 回答 2

0

坏线是这个

@reparator.skills = params[:skills]

params[:skills]是一个字符串数组(已传递的 id),但该skills=方法期望得到实际的实例,Skill因此会爆炸。

除了skills=, mongoid 还为您提供了一种skill_ids=方法,该方法允许您通过分配一个 id 数组来更改关联的对象。或者,加载你自己的技能对象,然后@reparator.skills = skills

于 2012-07-23T14:04:32.620 回答
0

我认为您的规范中有错字。post :create, :reparator => valid_attributes, :skills => skills_ttributes应该post :create, :reparator => valid_attributes, :skills => skills_attributes改为。

于 2012-07-22T11:14:04.713 回答