Jack-of-some
Jack-of-some

Reputation: 413

Ruby rspec mocking a class with an attribute that is a hash

I have a class I am testing, call it myfoo. It accesses a class called yourbar. Specifically something like this...

yourbar_obj.projects[project_name]

In my spec code I have this

let(:yourbar_obj) { Class.new }

and I want to mock it to respond to the hash attribute access. So I tried this

expect(yourbar_obj).to receive(projects).and_return(some_obj)

But when I run the code it says

NoMethodError: undefined method `projects' ...

Is it possible to mock a hash access like that? The same type of thing works for regular method calls. I even tried adding a .with(project_name) just in case. Same error. thoughts?

Upvotes: 2

Views: 1817

Answers (1)

Jack-of-some
Jack-of-some

Reputation: 413

Thanks to Max's help. Here is the correct answer...

some_hash_obj[project_name] = some_obj
expect(yourbar_obj).to receive(:projects).and_return(some_hash_obj)

Two key parts. The : before projects, and some_hash_obj must be a hash. I was trying to return the value (which was an obj) at the hash index in one shot, but that ain't how it works. return the hash, and the [] will apply to it.

Upvotes: 1

Related Questions