Search code examples
ruby-on-railsrubyruby-on-rails-3rspecrspec-rails

testing a method with should_receive using rspec


I have address method which instantiates a new class and returns some information.

class Office  
  attribute :id
  def address
    info = Services::Employee.new
    info.contact = [contact]
    info.id = id

    info
  end
end

Now in the above address method contact(one inside an array) is another method which returns a bunch of things.

Now in my rspec test I just want to say the info.contact returns [contact] without actually testing it with data. I read about should_receive but i am not sure how to test the above method using should_receive.

Here is what I tried:

info = Employee.deserialize(JSON.parse(info.to_json))
it 'returns info' do
  Employee.should_receive(:info.contact).and_return('[contact]')
  expect(helper.address).to eq(info)
end

I got this error:

   expected: 1 time with any arguments
   received: 0 times with any arguments

Solution

  • It looks like info is an instance of Employee within your test. Therefore it is Employee which receives the message contact.

    Try changing your test such that the should_receive is placed on Employee directly:

    Employee.any_instance.should_receive(:contact).and_return('[contact]')