【问题标题】:Mocks or factories in unit tests for a Rails controller?Rails 控制器的单元测试中的模拟或工厂?
【发布时间】:2016-02-16 04:15:05
【问题描述】:

我有一个DashboardController 和一个index 方法,它与我的User 模型进行交互:

def index
  user = User.first
  log_data = user.logs
  # more controller code here that uses the log_data
end

我正在为此index 方法编写控制器规范。我为我的用户模型定义了一个 FactoryGirl 工厂。在为此的单元测试中,我应该在这里用某种instance_double 模拟user,还是应该用FactoryGirl 创建一个User 对象?是否有关于如何测试控制器的约定/标准/趋势?

【问题讨论】:

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


    【解决方案1】:

    我会说没有必要模拟用户对象——它只会让你的规格离现实更远。您可以像这样愉快地设置您的规格:

    describe DashboardController, :type => :controller do
    
      let(:user) { create(:user) }
    
      describe "#index" do
        it "your test here" do
          ####
        end
      end
    
    end
    

    在您访问current_user 对象的另一种情况下,您可以尝试使用以下方法:

    let(:user) { create :user }
    
    before do
      allow(controller).to receive(:current_user).and_return(user)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多