[rspec-users] Speccing private class methods
dchelimsky at gmail.com
Thu Dec 21 07:59:45 EST 2006
On 12/21/06, Ashley Moran <work at ashleymoran.me.uk> wrote:
> How can I specify that a private method of a class gets called? If
> you run the code below, only spec (1) passes. Spec (2) is what I
> found causing problems in my code, and class (3) is my failed attempt
> to work around it. (3 really puzzles me - why is a private class
> method not accessible via send?)
> Another problem is that stub! makes public methods, which changes the
> behaviour of a class if you stub a private method.
In theory you shouldn't be specifying anything about private methods.
The only reason we support partial mocks at all (which is a mocking
no-no) is because Rails forces us to.
You won't find a solution to your problem within RSpec, but you can do this:
specify "(2) call_private_method should call private_method" do
MyClass.send :public, 'private_method'
MyClass.should_receive(:private_method).and_return("this is private")
MyClass.send :private, 'private_method'
So, for this spec only, you can access the method to spec that it gets
called, but then restore the method to its private state.
> require 'spec'
> class MyClass
> class << self
> def call_private_method
> def private_method
> "this is private"
> context "MyClass" do
> specify "(1) call_private_method should upcase the
> private_method" do
> MyClass.call_private_method.should == "THIS IS PRIVATE"
> specify "(2) call_private_method should call private_method" do
> MyClass.should_receive(:private_method).and_return("this is
> specify "(3) private_method should return 'this is private'" do
> MyClass.send(:private_method).should == "this is private"
> rspec-users mailing list
> rspec-users at rubyforge.org
More information about the rspec-users