2016-01-22 75 views
0

作为一个练习,我试图用rails-api gem来构建一个API,但是我不明白这个代码有什么问题。 有没有我没有看到的错误? 我使用的铁轨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 

错误运行此命令“rspec的投机/”:

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)>' 
+0

检查你正在渲染的错误? :) – sevenseacat

+0

我的问题解决了,但我很好奇,我该如何检查错误? – NeimadTL

+0

@ Neimad971你可以使用'byebug' gem并在你调用它并调试你的代码的地方停止执行。 – miligraf

回答

0

在你创建的方法,如果模型无效,那么代码将永远不会达到render语句。在这种情况下,导轨将假定状态为: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 
+0

你提供了一个见解:它是因为内容的长度在规范(42个字符,根据我的验证应该是最低60)。 – NeimadTL

+0

是“if @ object.valid?创建方法中的良好模式?感谢您的洞察力 – NeimadTL

+0

一如既往,取决于您的需求。我的办公室倾向于使用'if @ object.save'和'if @ object.update'因为这些会失败或通过取决于对象是否有效。 –

相关问题