如何在RSpec中使用class_double存根类方法?

时间:2021-02-09 20:23:23

I’m trying to write a simple isolated test for a controller method in my Rails 4 app. The method takes an ID from a query string, asks the Project model to give me some rows from the persistence layer, and render the result as JSON.

我正在尝试在我的Rails 4应用程序中为控制器方法编写一个简单的隔离测试。该方法从查询字符串中获取ID,要求Project模型为持久层提供一些行,并将结果呈现为JSON。

class ProjectsController < ApplicationController

  def projects_for_company
    render json: Project.for_company(params[:company_id])
  end

end

I’m struggling with stubbing the for_company method. Here is the code I’m trying:

我正在努力使用for_company方法。这是我正在尝试的代码:

require "rails_helper"

describe ProjectsController do

  describe "GET #projects_for_company" do

    it "returns a JSON string of projects for a company" do
      dbl = class_double("Project")
      project = FactoryGirl.build_stubbed(:project)
      allow(dbl).to receive(:for_company).and_return([project])
      get :projects_for_company
      expect(response.body).to eq([project].to_json)
    end

  end

end

Since I’ve stubbed the for_company method, I expect the implementation of the method to be ignored. However, if my model looks like this:

由于我已经存根了for_company方法,我希望忽略该方法的实现。但是,如果我的模型看起来像这样:

class Project < ActiveRecord::Base

  def self.for_company(id)
    p "I should not be called"
  end

end

…Then I can see that I should not be called is actually printed to the screen. What am I doing wrong?

...然后我可以看到我不应该被调用实际打印到屏幕上。我究竟做错了什么?

1 个解决方案

#1


6  

class_double doesn't actually replace the constant. You can call as_stubbed_const to replace the original

class_double实际上并不替换常量。您可以调用as_stubbed_const来替换原始文件

class_double("Project").as_stubbed_const

This is the just a convenience wrapper around stub_const

这只是stub_const的一个便利包装器

#1


6  

class_double doesn't actually replace the constant. You can call as_stubbed_const to replace the original

class_double实际上并不替换常量。您可以调用as_stubbed_const来替换原始文件

class_double("Project").as_stubbed_const

This is the just a convenience wrapper around stub_const

这只是stub_const的一个便利包装器

相关文章