强制控制器使用current_user进行模拟

时间:2010-07-07 00:13:38

标签: ruby-on-rails unit-testing rspec stub mocha

我试图在我的RSpec测试中指定我的控制器应该使用current_user.projects.find()而不是Project.find()我正在使用Mocha模拟框架并尝试这样的事情:

controller.current_user.projects.expects(:find).returns(@project)

我已经嘲笑controller.stubs(:current_user).returns(@profile)

即使我使用Project.find()实现,此测试也会通过此测试。如何测试我的控制器是否正在调用正确的对象?

编辑(添加其他代码):

我有项目和任务,项目有很多任务。这是在current_user

拥有的项目中显示任务的show方法

控制器中的动作:

def show
    @project = current_user.projects.find_by_id(params[:cardset_id])

    if @project.nil?
      flash[:notice] = "That project doesn't exist. Try again."
      redirect_to(projects_path)
    else
      @task = @project.tasks.find_by_id(params[:id])
    end
  end

这是不检查cardsets方法是否从current_user对象调用的测试。

当前测试:

context "with get to show" do
  context "with valid project" do
    before(:each) do
      @project = Factory(:project)
      @task = Factory(:task)
      @profile = @project.profile
      ApplicationController.stubs(:require_user).returns(true)
      controller.stubs(:current_user).returns(@profile)

      Project.stubs(:find_by_id).returns(@project)
      @project.tasks.stubs(:find_by_id).returns(@task)
      get :show, :project_id => @project.id, :id => @task.id
    end

    it "should assign task" do
      assigns[:task].should_not be_nil
    end

    it "should assign project" do
      assigns[:project].should_not be_nil
    end
  end

  context "with invalid project" do
    before(:each) do
      Project.stubs(:find_by_id).returns(nil)
      get :show, :project_id => @project.id, :id => @task.id
    end

    it "should set flash" do
      flash[:notice].should match(/doesn't exist/i)
    end

    it "should redirect" do
      response.should redirect_to(cardsets_url)
    end
  end
end

1 个答案:

答案 0 :(得分:0)

根据你告诉我们的小事,我认为你需要:

@profile.expects(:find).returns(@project)