Search code examples
ruby-on-railsrubyrspecrspec-rails

How to build chained methods like - should_receive(:something).with(:params, values).and_return(:something_else)


I was trying to make my code a bit smaller building a method that can look like the should_receive from RSpec, the case here is that I'm testing a state machine and I have several methods with code like this:

context "State is unknown" do
  before do
    @obj = create_obj(:state => 'unknown')
  end
  context "Event add" do
    it 'should transition to adding if not in DB' do
      @obj.add
      @obj.state.should == 'adding'
    end

    it 'should transition to linking if already in DB' do
      create_obj_in_db
      @obj.add
      @obj.state.should == 'linking'
    end
  end
end

I want to replace these lines of code to something similar to this:

@obj.should_receive(:add).and_transition_to('adding')
@obj.should_receive(:modify).and_transition_to('modifying')

How are these methods built?


Solution

  • The important part to chaining is to return self from the object, so the next call can still work on the object.

    class Foo
      def one
        puts "one"
        self
      end
    
      def two
         puts "two"
         self
      end
    
      def three
         puts "three"
         self
      end
    end
    
    a=Foo.new
    a.one.two.three