Cameron Bass Cameron Bass - 5 months ago 23
Ruby Question

expected result to have changed by 1, but was changed by 0

I'm new to RSpec and this error is all new to me. Everything seems routine so I can't seem to debug this issue myself. ERROR: expected result to have changed by 1, but was changed by 0. I'll post my code for clarity.

SUBSCRIBER FACTORY:

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

Answer

Here, you're showing your subscriptions controller, expecting one of its actions to be hit. However, your test case is actually calling the create route of the Comments controller.

When, in your test case, you write describe SubscribersController do, you are establishing a scope for the HTTP requests you make in that block.

So when you call post :create, subscriber: subscriber, comment: comment, it's the Comments controller which is being hit.

In general, in order to debug, you should

  1. check that the area of code in question is being called
  2. check that values are correct (here, that would mean that the Comment.create object is successfully saved.
Comments