我是RSpec的新手,这个错误对我来说都是新手。一切似乎都很常见,所以我似乎无法自己调试这个问题。错误:预期结果已更改为1,但已更改为0.为了清晰起见,我会发布我的代码。
订阅者工厂:
FactoryGirl.define do
factory :subscriber do
first_name "Tyler"
last_name "Durden"
email "tyler@example.com"
phone_number "8765555"
end
end
CONTROLLER:
class CommentsController < ApplicationController
def new
@comment = Comment.new
end
def create
@subscriber = Subscriber.order('updated_at desc').first
@comment = @subscriber.comments.build(comments_params)
if @comment.save
flash[:notice] = "Thank you!"
redirect_to subscribers_search_path(:comments)
else
render "new"
end
end
private
def comments_params
params.require(:comment).permit(:fav_drink, :subscriber_id)
end
end
SPEC:
require "rails_helper"
describe SubscribersController do
include Devise::TestHelpers
let(:user) { FactoryGirl.create(:user) }
let(:subscriber) { FactoryGirl.attributes_for(:subscriber) }
it "creates a new comment" do
sign_in(user)
comment = FactoryGirl.attributes_for(:comment)
expect { post :create, subscriber: subscriber, comment: comment }.to change{ Comment.count }.by(1)
end
end
ERROR:
Failure/Error: expect { post :create, subscriber: subscriber, comment: comment }.to change{ Comment.count }.by(1)
expected result to have changed by 1, but was changed by 0
# ./spec/controllers/comment_spec.rb:13:in `block (2 levels) in <top (required)>'
答案 0 :(得分:2)
在这里,您正在显示您的评论控制器,期望其中一个操作被点击。但是,您的测试用例实际上是调用订阅控制器的create
路由。
在测试用例中,当您编写describe SubscribersController do
时,您正在为在该块中进行的HTTP请求建立范围。
所以当你致电post :create, subscriber: subscriber, comment: comment
时,
它是正在被击中的订阅控制器。
一般来说,为了调试,你应该
Comment.create
对象已成功保存。