Skip to content

Instantly share code, notes, and snippets.

@joekr
Last active December 25, 2015 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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
@joekr
Copy link
Author

joekr commented Oct 18, 2013

The error I get is:

NoMethodError: private method `my_private_method?' called for #User:0x007fed4c3d91e0

@cheshire137
Copy link

line 9: RSpec style is not name tests with "should" :)

@cheshire137
Copy link

Doubt it will affect it, just a style thing, but I'd do expect(user.my_public_method).to be_true

@cheshire137
Copy link

I use Machinist over FactoryGirl, and that does create an actual instance of the model. If FactoryGirl is making a fake, that could be your problem where it only fakes the public interface.

@cheshire137
Copy link

Hm, and in RSpec, even with FactoryGirl, I would do subject { FactoryGirl.create(:user) } and then expect(subject.my_public_method).to be_true

@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