jws
jws

Reputation: 2764

How to mock mongodb in rspec (beginner)

I am an old programmer, but new to ruby, and thrown into an existing code base where I need to extend an rspec test.

The code that needs to be tested uses MongoDB (mongoid), and has a pattern similar to this:

 objects = Database::MyTable.active.where(object_id: object_id).to_a

I want my rspec code to provide the objects hard-coded in the test. How can I do that?

Upvotes: 2

Views: 1224

Answers (2)

D. SM
D. SM

Reputation: 14490

I would separate the code that retrieves the data (including the line you mentioned) into one method and the code that consumes/operates on the data into another method, then mock the entire retrieval method. This way you don't need to muck with the exact queries used.

Upvotes: 0

Jared Beck
Jared Beck

Reputation: 17528

Because of the "chain" of methods, stubbing is a little awkward, but it can be done.

allow(Database::MyTable).to(
 receive(:active).and_return(double(
   where: [{ id: 1 }, { id: 2 }] 
 ))
)

We have stubbed active to return a mock (a double) on which we stub where.

Docs: rspec-mocks

PS: There are many other ways to write these stubs, some objectively better, some subjectively better. There are also ways to refactor your code to make stubbing easier.

PPS: Welcome to ruby!

Upvotes: 1

Related Questions