为什么要使用此视图模板?

时间:2015-12-26 19:06:41

标签: ruby-on-rails ruby model-view-controller integration-testing

我有一个控制器方法来验证收到带有令牌的链接的用户(请参阅底部的方法)。我有一个集成测试:

def test
  get login_path('invalid token')     // Login_path routes to the controller method below.
  assert flash[:danger]
  assert_redirected_to root_path
end

此测试产生以下错误(指get login_path('invalid token')):

ActionView::MissingTemplate: Missing template invitations/login, application/login with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. 

视图invitiations/login确实不存在。但是,根据下面的控制器方法,它永远不需要这样的视图(它总是重定向到root_path或呈现profiles/show)。可能导致此错误的原因是什么?

控制器方法:

def login
  inv = Invitation.where('email = ?', params[:email])
  if inv
    inv.each do |person|
      if person.authenticated?(:invitation, params[:id])
        @organization = person.organization
        unless @organization.nil?
          render 'profiles/show' and return
        else
          flash[:danger] = "Error"
          redirect_to root_path and return
        end
      end
      flash[:danger] = "Invalid link"
      redirect_to root_path
    end
  else
    flash[:danger] = "Invalid link"
    redirect_to root_path
  end
end

P.S。用于传递的测试,即直到我重写了控制器方法以适应多个inv(见Retrieve multiple records with find_by method)。

1 个答案:

答案 0 :(得分:1)

您使用if inv - 如果没有匹配电子邮件的邀请,这仍会返回true,因为inv是ActiveRecord查询对象。但是each没有做任何事情,即没有明确重定向或呈现。将调用默认渲染并期望存在模板。

使用if inv.present?将解决此问题。

(另外,您可能希望确保inv集合仅包含一个结果。在同一请求中多次重定向或呈现将导致错误。)