For example, I have this scenario where a Directory model will only save
if
it can connect to the LDAP server. In a test I’m writting, though,
connecting to the LDAP server is not relevant, so I tried doing this:
context “LDAP is on” do
before(:each) do
Directory.stub!(:authenticate_user).and_return(@user). @account.directory = Directory.make :ldap_on
end
…
end
However, the Directory.make fails (since the before_save ldap test
fails,
because authenticate_user can’t connect to the LDAP server). The issue
is
that it stubs the method as a singleton method of Directory.
One alternative is opening the Directory class and redefining the
authenticate_user method, but I’d like to know if rSpec supports somehow
stubing a class and let it stub instance too.
On Apr 4, 2010, at 11:21 PM, Marcelo de Moraes S. wrote:
However, the Directory.make fails (since the before_save ldap test fails, because authenticate_user can’t connect to the LDAP server). The issue is that it stubs the method as a singleton method of Directory.
That is how stubbing works in RSpec, and every other Ruby
stubbing/mocking framework I know of. If you tell a class to stub a
method, it stubs a class method. If you want to stub an instance method,
you stub it directly on an instance. Mocha has an any_instance method,
which RSpec doesn’t have (yet), that allows you to say:
One alternative is opening the Directory class and redefining the authenticate_user method, but I’d like to know if rSpec supports somehow stubing a class and let it stub instance too.
I don’t think you’d want to stub the same method on the class and
instance automatically. You might end up with false positives when one
object calls a class method on an instance.
HTH,
David
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.