错误:分配属性时,必须传递散列作为参数

Han*_*oki 11 ruby ruby-on-rails

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

document.rb

class Document < ActiveRecord::Base
  validates_presence_of :name
  has_many :votes
end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

然而,当我跑去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)>'
Run Code Online (Sandbox Code Playgroud)

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

Yan*_*lly 8

问题出在您的控制器中.

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