这个规范和控制器代码有什么问题?

时间:2012-08-30 20:48:08

标签: ruby-on-rails ruby rspec

我正在尝试使用rspec测试现有的rails项目。我想测试一个控制器,但得到一个我无法解决的错误:S

这是我的规范代码;

require 'spec_helper'

describe BriefNotesController do

  before(:all) do
    @customer=Factory(:customer)
    @project=Factory(:project_started, :owner => @customer)
  end

  context 'get :new' do

    it 'should redirect to login page for not signed in users' do
      get :new, :project_id => @project.id
      response.should redirect_to("/kullanici-girisi")
    end

    it 'should be success and render new brief note page for project owner' do
      sign_in @customer
      get :new, :project_id => @project.id
      response.should be_success
    end

  end

end

这是我的控制器代码;

class BriefNotesController < ApplicationController
  before_filter :authenticate_user!
  before_filter :find_project

  def new
    @brief_note = @project.brief_notes.new
  end

  def create
    @brief_note = @project.brief_notes.build(params[:brief_note])
    if @brief_note.save
      redirect_to brief_project_path(@project)
    else
      render :action => :new
    end
  end

private
  def find_project
    @project = current_user.projects.find_by_cached_slug([params[:project_id]])
  end
end

我认为current_user.projects.find_by_cached_slug方法不起作用。所以这是错误;

Failures:

  1) BriefNotesController get :new should be success and render new brief note page for         project owner
 Failure/Error: get :new, :project_id => @project.id
 NoMethodError:
   undefined method `brief_notes' for nil:NilClass
 # ./app/controllers/brief_notes_controller.rb:6:in `new'
 # ./spec/controllers/brief_notes_controller_spec.rb:19:in `block (3 levels) in <top (required)>'

2 个答案:

答案 0 :(得分:1)

错误来自您的find_project过滤器:find_by_cached_slug返回nil,分配给@project,并在brief_notesnew时触发未定义的方法错误呼吁它(在new行动中)。

从您的规范说明中我假设它甚至不应该执行authenticate_user!代码,而是重定向到{{1}}?我自己不使用设计(这是一种设计方法,对吧?)所以我不确定该方法的细节,但我认为这就是你的问题所在。

我认为问题不在于您的FactoryGirl语法,该语法已被弃用但仍应有效。

答案 1 :(得分:1)

如果没有关于模型的更多信息,我无法确定,但可能的罪魁祸首是您将@project.id作为请求参数传递,但是您正在通过cached_slug进行查找。请尝试@ project.to_param。