简体   繁体   中英

How to access to test (devise) current_user in a helper?

I have used current_user in a helper as following:

module InvestorsHelper
  def single?
    binding.pry
    current_user.kyc.marital_status == 'Single'
  end

  def married?
    current_user.kyc.marital_status == 'Married'
  end

  def politically_exposed?
    current_user.kyc.is_politically_exposed.present?
  end

  def tax_residency?
    current_user.kyc.is_tax_residency.present?
  end
end

But how do I test those methods in rspec testing?

I wrote the following rspec code:

context "Investors Helper" do
    before(:each) do
      puts "Befpre exljfgd"
      current_user =    @user ||= FactoryGirl.create(:user)
      @kyc  ||= FactoryGirl.create(:kyc, user_id: @user.id)
    end

  describe InvestorsHelper, '#single?' do
    it 'returns status of current user' do

      result = InvestorsHelper.single?
      binding.pry
    end
end

end end

But it returns the error: NameError:

   undefined local variable or method `current_user' for InvestorsHelper:Module

What am I doing wrong?

In your example InvestorsHelper doesn't define current_user , so you are getting that error message. It looks like InvestorsHelper is meant to be a mix-in, so I would either test something it's mixed into instead or mix it into a mock class that defines current_user and test that.

In addition, I'm surprised your code fails there and not on InvestorsHelper.single? . Calling the method like that will try to call the singleton method ::single? (usually defined with def self.single? ) but you've declared it as an instance method in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM