Boko
Boko

Reputation: 23

Rails 3.2.9.Testing observer with RSpec(trouble with should_receive)

I have such problem. My test checks whether the Observer called, but does not execute it. My files:


todo_observer.rb:

class TodoObserver < ActiveRecord::Observer     
  def after_create(todo)
   todo.add_log('creating')
  end    
 end

todo.rb:

class Todo < ActiveRecord::Base
  attr_accessible :content, :done, :order

  validates :content, :presence => true,
            :length => {:minimum => 2}

  def add_log(event)
    Logdata.start_logging(self.content, event)
  end
end

logdata.rb

class Logdata < ActiveRecord::Base
  attr_accessible :modification, :event

  def self.start_logging(content, event)
    Logdata.create!(:modification => content, :event => event)
  end
end

todo_observer_spec.rb:

require 'spec_helper'

describe TodoObserver do

  before(:each) do
    @attr = { :modification => "Example", :event => 'Event' }
    @attr_todo = { :content => "Example", :done => :false }
  end

  describe 'after_create' do
    it "should create log about creating task" do
      count_log = Logdata.all.size
      todo = Todo.new(@attr_todo)
      todo.should_receive(:add_log).with('creating')
      todo.save!
      (Logdata.all.size).should eq(count_log + 1)
    end
  end

end

When I run test I get such error

Failure/Error: (Logdata.all.size).should eq(count_log + 1)

   expected: 1
        got: 0

Its mean, that observer called,but doesn't create instance of Logdata. When I comment string(check the call)

todo.should_receive(:add_log).with('creating')

My tests were successful.And accordingly its success when I comment string (Logdata.all.size).should eq(count_log + 1)and uncomment previous string. How does the function should_receive to create an instance of the class Logdata?

Upvotes: 0

Views: 949

Answers (1)

Daniel Evans
Daniel Evans

Reputation: 6808

should_receive prevents the actual method from being called.

You should create two separate tests. One to check that the log is added to the todo, and one to check that the log is created.

describe 'after_create' do
  it "should add a log to the todo" do
    todo = Todo.new(@attr_todo)
    todo.should_receive(:add_log).with('creating')
    todo.save!
  end

  it "should create a new logdata" do
    todo = Todo.new(@attr_todo)
    expect {
      todo.save!
    }.to change {Logdata.count}.by(1)
  end
end

Upvotes: 1

Related Questions