我试图理解为什么我的rspec测试不起作用,而我的实际代码是创建新记录的。
我得到的错误是:失败/错误:
expect {
post "/products/", params: {product: attributes_for(:product)}, as: :json
}.to change(Product, :count).by(1)
expected #count to have changed by 1, but was changed by 0
我试图实际使用代码,它似乎添加了一条新记录,但我不太清楚为什么测试不起作用。我是否错误地写了测试?
的ProductsController
def create
@p = Product.new(product_params)
@p.save
redirect_to action: :new
end
产品< ApplicationRecord
class Product < ApplicationRecord
validates :title, presence: true #--- Presence
validates :title, length: { minimum: 2 } #--- Minimum 2
validates :title, :description, length: { maximum: 1000 } #--- Maximum 1000
end
ProductSpec
require 'rails_helper'
require 'pp'
RSpec.describe "ProductsRequests", type: :request do
#--- New
describe "#new" do
context "logged in as guest" do
before :each do
get new_product_path
end
it { expect(assigns(:p)).to be_a_new(Product) }
it { expect(response).to render_template :new }
end#--- Guest New
end #--- New
#--- Create
describe "#create" do
context "logged in as guest" do
it "creates new record" do
expect{
post "/products/", params: {product: attributes_for(:product)}
}.to change(Product, :count).by(1)
end
end #--- Guest Create
end #--- Create
答案 0 :(得分:0)
调试它的最快方法是将save
更改为控制器中的save!
。
save
尝试保存,如果失败则返回false,因此您可能希望使用它并稍后添加一些处理(错误在@p.errors
中),但现在要快速查看发生了什么使用save!
- 如果出现任何错误(包括验证),它会引发异常。