[rspec-users] Private method in custom module

David Chelimsky dchelimsky at gmail.com
Thu Dec 31 14:04:48 EST 2009


On Thu, Dec 31, 2009 at 12:54 PM, Phillip Koebbe <phillipkoebbe at gmail.com>wrote:

> I have a module of custom examples, such as
>
> module ControllerHelperMethods
>        module MyExampleGroupMethods
>                def should_set_the_body_id(body_id)
>                        it "should set the body id to '#{body_id}'" do
>                                assigns[:body_id].should == body_id
>                        end
>                end
>        end
>
>        def self.included(receiver)
>                receiver.extend MyExampleGroupMethods
>        end
> end
>
> and in spec_helper:
>
> Spec::Runner.configure do |config|
>        config.include(ControllerHelperMethods, :type => :controllers)
> end
>

First of all, you can simplify this by using extend() instead of include()
on the config object:

module ControllerMacros
  def should_set_the_body_id(body_id)
    it "should set the body id to '#{body_id}'" do
      assigns[:body_id].should == body_id
    end
  end
end

Spec::Runner.configure do |config|
  config.extend(ControllerMacros, :type => :controllers)
end

Note that we generally referred to as "macros," so I recommend using that
name for consistency.


> I have duplicate code in two of my custom examples, so I want to
> refactor it to a private method, but I can't seem to get the private
> method to work. I have tried the most obvious way (private keyword
> followed by the method), and also a couple of more clever approaches
> that involved doing an instance_eval in self.included.
>

I *think* that if you use extend instead of include + included hook, you can
just use the private keyword and all will be well.

HTH,
David


> First, should I be able to call private methods in my custom examples?
> If so, how.
>
> Peace.
> Phillip
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20091231/ae6afd61/attachment-0001.html>


More information about the rspec-users mailing list