Use #instance_eval
@controller = AccountController.new
@controller.instance_eval{ current_account } # invoke the private method
@controller.instance_eval{ @current_account }.should eql ... # check the value of the instance variable
I use send method. Eg:
event.send(:private_method).should == 2
Because "send" can call private methods
Where is the current_account method being used? What purpose does it serve?
Generally, you don't test private methods but rather test the methods that call the private one.
You should not test your private methods directly, they can and should be tested indirectly by exercising the code from public methods.
This allows you to change the internals of your code down the road without having to change your tests.
You could make you private or protected methods as public:
MyClass.send(:public, *MyClass.protected_instance_methods)
MyClass.send(:public, *MyClass.private_instance_methods)
Just place this code in your testing class substituting your class name. Include the namespace if applicable.
require 'spec_helper'
describe AdminsController do
it "-current_account should return correct value" do
class AccountController
def test_current_account
current_account
end
end
account_constroller = AccountController.new
account_controller.test_current_account.should be_correct
end
end
Unit testing private methods seems too out of context with the behaviour of the application.
Are you writing your calling code first? This code is not called in your example.
The behaviour is: you want an object loaded from another object.
context "When I am logged in"
let(:user) { create(:user) }
before { login_as user }
context "with an account"
let(:account) { create(:account) }
before { user.update_attribute :account_id, account.id }
context "viewing the list of accounts" do
before { get :index }
it "should load the current users account" do
assigns(:current_account).should == account
end
end
end
end
Why do u want to write the test out of context from the behaviour you should be trying to describe?
Does this code get used in a lot of places? Need a more generic approach?
https://www.relishapp.com/rspec/rspec-rails/v/2-8/docs/controller-specs/anonymous-controller
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With