预期结果已更改为1,但已更改为0

时间:2016-06-21 16:50:45

标签: ruby-on-rails ruby rspec

我是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)>'

1 个答案:

答案 0 :(得分:2)

在这里,您正在显示您的评论控制器,期望其中一个操作被点击。但是,您的测试用例实际上是调用订阅控制器的create路由。

在测试用例中,当您编写describe SubscribersController do时,您正在为在该块中进行的HTTP请求建立范围

所以当你致电post :create, subscriber: subscriber, comment: comment时, 它是正在被击中的订阅控制器。

一般来说,为了调试,你应该

  1. 检查是否正在调用相关代码区域
  2. 检查值是否正确(此处,这意味着Comment.create对象已成功保存。