Search code examples
rubyrspecmockingstubsequel

Multiple joins mocks and Rspec


I'm trying to mock this statement, but I can't find anything on the internet to help me:

  someone_ids = Office.join(:address, id: :address_id)
                      .join(:office_someone, id: :id)
                      .pluck(:someone_id)

Here is the spec that I'm using:

  expect(Office).to receive(:join)
                .with(:office_someone, { :id => :id })
                .with(:address, { :id => :address_id })
                .and_return([1])

Does anybody know how to mock multiple join? I'm using Sequel.


Solution

  • Previously RSpec had a stub_chain method that allowed you to do something like that easily, however it was removed because it encouraged bad practices, and now you'll have to stub each response manually:

    office = instance_double(Office)
    expect(Office).to receive(:join)
                  .with(:address, { :id => :address_id })
                  .and_return(office)
    expect(office).to receive(:join)
                  .with(:office_someone, { :id => :id })
                  .and_return(office)
    expect(office).to receive(:pluck).with(:someone_id).and_return([1])
    

    Which if its a code that you find yourself repeating too much will made you think about refactoring it, which in the end is one of the reasons people do testing: "If its hard to test, it might not be well designed"