错误:分配属性时,必须将哈希作为参数传递

时间:2014-08-04 08:59:21

标签: ruby-on-rails ruby

嗨我刚刚开始使用ruby,我正在编写控制器和控制器规格,但我有一些问题。

document.rb

class Document < ActiveRecord::Base
  validates_presence_of :name
  has_many :votes
end

documents_controller.rb

class API::DocumentsController < ApplicationController
  def create
    @document = Document.new(:name)
    if @document.save
      @document.update_attributes(name: @document.name.url) if document_params[:name].present?
      render json: @document, serializer: DocumentSerializer, status: 201
    else
      render json: @document.errors, status: 422
    end
  end
end

documents_controller_spec.rb

  describe "POST 'index'" do
    before { @attr = FactoryGirl.attributes_for(:document) }

    describe "failure" do
      describe "with missing parameters" do
        before { @attr.each { |key,value| @attr[key] = nil } }
        it "should not create a new record" do
          lambda { post :create, document: @attr }.should_not change(Document, :count)
        end
      end
    end
  end

但是,当我运行bundle exec rspec spec试用我的测试时,我收到了一个错误:

Failure/Error: lambda { post :create, document: @attr }.should_not change(Document, :count)                                                                                                                                                                                  
     ArgumentError:                                                                                                                                                                                                                                                               
       When assigning attributes, you must pass a hash as an argument.                                                                                                                                                                                                            
     # ./app/controllers/api/documents_controller.rb:8:in `create'                                                                                                                                                                                                                
     # ./spec/controllers/api/documents_controller_spec.rb:29:in `block (6 levels) in <top (required)>'                                                                                                                                                                           
     # ./spec/controllers/api/documents_controller_spec.rb:29:in `block (5 levels) in <top (required)>'

任何人都可以对此有所了解吗?

1 个答案:

答案 0 :(得分:8)

问题出在您的控制器中。

  def create
    @document = Document.new(:name) # :name is a symbol, not a Hash like params for example