Skip to content

Instantly share code, notes, and snippets.

@joekr
Last active December 25, 2015 21:49
Show Gist options
  • Save joekr/7045514 to your computer and use it in GitHub Desktop.
Save joekr/7045514 to your computer and use it in GitHub Desktop.
Rspec a public method which calls a private method.
class User < ActiveRecord::Base
def my_public_method
self.my_private_method
end
private
def my_private_method
true
end
end
require 'spec_helper'
describe User do
before(:each) do
@user = FactoryGirl.create(:user)
end
it "should return true" do
user.my_public_method.should eq(true)
end
end
@cheshire137
Copy link

OMG just did this in IRB:

>> class User
>>
?>   def my_public_method
>>     self.my_private_method
>>   end
>>
?>   private
>>
?>   def my_private_method
>>     true
>>   end
>>
?> end
=> nil
>> user = User.new
=> #<User:0x007fa0cc873d30>
>> user.my_public_method
NoMethodError: private method `my_private_method' called for #<User:0x007fa0cc873d30>
  from (irb):4:in `my_public_method'
  from (irb):15
  from /Users/sarah/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'

@cheshire137
Copy link

Don't use self!

>> class User
>>
?>   def my_public_method
>>     my_private_method
>>   end
>>
?>   private
>>
?>   def my_private_method
>>     true
>>   end
>>
?> end
=> nil
>> user = User.new
=> #<User:0x007fb0231def68>
>> user.my_public_method
=> true

@cheshire137
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment