Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 691 Vote(s) - 3.55 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is there a way to stub a method of an included module with Rspec?

#1
I have a module that is included in another module, and they both implement the same method.
I would like to stub the method of the included module, something like this:

module M
def foo
:M
end
end

module A
class << self
include M

def foo
super
end
end
end

describe "trying to stub the included method" do
before { allow(M).to receive(:foo).and_return(:bar) }

it "should be stubbed when calling M" do
expect(M.foo).to eq :bar
end

it "should be stubbed when calling A" do
expect(A.foo).to eq :bar
end
end

The first test is passing, but the second one outputs:

Failure/Error: expect(A.foo).to eq :bar

expected: :bar
got: :M

Why isn't the stub working in this case?
Is there a different way to achieve this?

Thanks!

-------------------------------------UPDATE----------------------------------

Thanks! using allow_any_instance_of(M) solved this one.
My next question is - what happens if I use prepend and not include? see the following code:

module M
def foo
super
end
end

module A
class << self
prepend M

def foo
:A
end
end
end

describe "trying to stub the included method" do
before { allow_any_instance_of(M).to receive(:foo).and_return(:bar) }

it "should be stubbed when calling A" do
expect(A.foo).to eq :bar
end
end

This time, using allow_any_instance_of(M) results in an infinite loop. why is that?
Reply

#2
Note you cannot directly call `M.foo`! Your code only seems to work because you mocked `M.foo` to return `:bar`.

When you open `A` metaclass (`class << self`) to include `M`, you have to mock any instance of `M`, that is adding to your `before` block:

`allow_any_instance_of(M).to receive(:foo).and_return(:bar)`

module M
def foo
:M
end
end

module A
class << self
include M

def foo
super
end
end
end

describe "trying to stub the included method" do
before do
allow(M).to receive(:foo).and_return(:bar)
allow_any_instance_of(M).to receive(:foo).and_return(:bar)
end


it "should be stubbed when calling M" do
expect(M.foo).to eq :bar
end

it "should be stubbed when calling A" do
expect(A.foo).to eq :bar
end
end

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through