您好我遇到了这个问题,我正在测试我的助手,它应该设置实例可用,但在测试时,当我使用它分配它总是返回nil
这是我的帮手:
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
这是测试
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
和控制台日志:
PublicHelper
popup_campaign
#<PopupCampaign:0x0000010bb64cc8>
should return valid instance (FAILED - 1)
失败:
1) PublicHelper popup_campaign should return valid instance
Failure/Error: expect(assigns(:popup_campaign)).to be_present
expected present? to return true, got false
有谁能告诉我我做错了什么?谢谢你:))
答案 0 :(得分:0)
我没有找到如何从助手分配实例变量。相反,我重构了代码,根本不使用实例,并测试部分是否渲染!
类似的东西:
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
测试:
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