作爲一個練習,我試圖用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)>'
檢查你正在渲染的錯誤? :) – sevenseacat
我的問題解決了,但我很好奇,我該如何檢查錯誤? – NeimadTL
@ Neimad971你可以使用'byebug' gem並在你調用它並調試你的代碼的地方停止執行。 – miligraf