[rspec-users] Speccing private class methods
David Chelimsky
dchelimsky at gmail.com
Thu Dec 21 07:59:45 EST 2006
On 12/21/06, Ashley Moran <work at ashleymoran.me.uk> wrote:
> Hi
>
> 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
begin
MyClass.send :public, 'private_method'
MyClass.should_receive(:private_method).and_return("this is private")
ensure
MyClass.send :private, 'private_method'
end
end
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.
>
> Ashley
>
>
> require 'spec'
>
> class MyClass
> class << self
> def call_private_method
> private_method.upcase
> end
>
> private
> def private_method
> "this is private"
> end
> end
> end
>
> context "MyClass" do
> specify "(1) call_private_method should upcase the
> private_method" do
> MyClass.call_private_method.should == "THIS IS PRIVATE"
> end
>
> specify "(2) call_private_method should call private_method" do
> MyClass.should_receive(:private_method).and_return("this is
> private")
> end
>
> specify "(3) private_method should return 'this is private'" do
> MyClass.send(:private_method).should == "this is private"
> end
> end
>
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>
More information about the rspec-users
mailing list