2016-01-22 84 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'因爲這些會失敗或通過取決於對象是否有效。 –

相關問題