为什么这个对象没有保存在数据库中?

时间:2016-01-22 14:52:58

标签: ruby-on-rails ruby rspec

作为练习,我尝试使用rails-api gem来构建API 我无法理解该代码的问题是什么。 我没有看到错误吗? 我使用的是rails 4.2.4

型号:

class Todo < ActiveRecord::Base

  validates :title, :presence => true, length: { minimum: 3, maximum: 32 }
  validates :content, :presence => true, length: { minimum: 60, maximum: 160 }

end

控制器:

class TodosController < ActionController::API


  def create
    @todo = Todo.new(todo_params)

    if @todo.valid?
      if @todo.save
        render json: @todo, status: :created, location: @todo
      else
        render json: @todo.errors, status: :unprocessable_entity
      end
    end
  end


  private

    def todo_params
      params.require(:todo).permit(:title, :content)
    end
end

规范:

require 'rails_helper'

RSpec.describe TodosController, type: :controller do

  describe "#create" do
    context "when JSON format" do
      describe "#create" do
        subject{ 
          post :create, { 
            :format => :json,
            :todo => { 
              :title => 'the title',
              :content => 'the content which is bigger than the title' 
            } 
          }
        }
        its(:status) { should == 200 } # OK

        it "saves the todo" do
          subject
          Todo.all.count.should == 1
        end
      end
    end
  end
end

运行此命令时出错&#34; rspec spec /&#34; :

F................

Failures:

1) TodosController#create when JSON format #create saves the todo
   Failure/Error: Todo.all.count.should == 1

     expected: 1
          got: 0 (using ==)
   # ./spec/controllers/todos_controller_spec.rb:21:in `block (5 levels) in <top (required)>'

1 个答案:

答案 0 :(得分:0)

在您的create方法中,如果模型无效,则代码将永远不会到达render语句。在这种情况下,rails将假定状态为:ok并呈现默认模板。

尝试重构您的代码,以便它始终匹配任何一种情况。

def create
  @todo = Todo.new(todo_params)

  if @todo.save # will be false if the save didn't work
    render json: @todo, status: :created, location: @todo
  else
    render json: @todo.errors, status: :unprocessable_entity
  end
end