ruby-on-railsrubyrspecshoulda

Shoulda matchers - delegate_method not working


I have a simple delegator class

class Service::Fs::Account < DelegateClass(Bank::Account)
  extend SingleForwardable

  def initialize(args={})
    @account = Bank::Account.new(args)
    super(@account)
  end

  def_delegators :"Bank::Account", :all, :create, :update
end

from my rails console, everything works fine

2.1.8 :002 > Service::Fs::Account.all
  Bank::Account Load (1.2ms)  SELECT "bank_accounts".* FROM "bank_accounts"
 => #<ActiveRecord::Relation []> 

This my spec for Account delegator class

require 'spec_helper'

describe Service::Fs::Account do
  describe 'delegations' do
    it { should delegate_method(:all).to(Bank::Account) }
  end
end

tests are failing with the following error

 Failure/Error: it { should delegate_method(:all).to(Bank::Account) }
   Expected Service::Fs::Account to delegate #all to #Bank::Account object
   Method calls sent to Service::Fs::Account#Bank::Account: (none)
 # ./spec/models/service/fs/account_spec.rb:5:in `block (3 levels) in <top (required)>'

can anyone help me figure out why this test is failing? Thank you


Solution

  • Instead of using should matchers, you can test this behavior explicitly using RSpec mocks

    it "delegates 'all' to Bank::Account" do
      expect(Bank::Account).to receive(:all)
      Service::Fs::Account.all
    end