Bitwise
Bitwise

Reputation: 8451

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 "[email protected]"
 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)>'

Upvotes: 1

Views: 1746

Answers (1)

max pleaner
max pleaner

Reputation: 26768

Here, you're showing your comments controller, expecting one of its actions to be hit. However, your test case is actually calling the create route of the Subscriptions 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 Subscriptions 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.

Upvotes: 2

Related Questions