简体   繁体   中英

rspec assigns() not working

Hello i ran in to this problem, i am testing my helper, and it should set instance vairable, but in test when i use assigns it allways retuns nil

Here is my helper:

def popup_campaign
    return "" if cookies["hide_popup_campaign"] == "1"
    popup = PopupCampaign.current(current_locale)
    @popup_campaign = popup.exists? && popup.first.active ? popup.first : false
    puts @popup_campaign # just cheking

    render :partial => 'layouts/shared/popup_campaign'
  end

and here is the test

it "should return valid instance" do
      popup.save(:validate => false)
      helper.request.cookies["hide_popup_campaign"] = "0"
      helper.stub(:current_locale).and_return("lv")
      helper.popup_campaign
      expect(assigns(:popup_campaign)).to be_present
    end

and console log:

PublicHelper
  popup_campaign
#<PopupCampaign:0x0000010bb64cc8>
    should return valid instance (FAILED - 1)

failure:

 1) PublicHelper popup_campaign should return valid instance
     Failure/Error: expect(assigns(:popup_campaign)).to be_present
       expected present? to return true, got false

Could anyone tell me what i am doing wrong? thank you :)

I did not find how to assign instance variables from helpers. Instead i refactured code to not use the instance at all and tested if partial is rendering or not!

something like this:

def popup_campaign
    return "" if cookies["hide_popup_campaign"] == "1"
    popup = PopupCampaign.current(current_locale)
    campaign = popup.exists? && popup.first.active ? popup.first : false

    render :partial => 'layouts/shared/popup_campaign', locals: {popup: campaign} if campaign
end

Test:

it "should render" do
      popup.save(:validate => false)
      helper.request.cookies["hide_popup_campaign"] = "0"
      helper.stub(:current_locale).and_return("lv")
      expect(helper.popup_campaign).to render_template('layouts/shared/popup_campaign') # or not_to 
    end

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