【问题标题】:rspec stub current_companyrspec 存根 current_company
【发布时间】:2011-02-22 03:03:12
【问题描述】:

我有一个 Rails 3 项目,我想将当前选择的公司存储在会话变量中。

我正在使用人员控制器规范,并且想暂时删除 current_company,因为我正在为人员新控制器操作隔离我的规范示例。

it "should call current_company" do 
  company = mock_model(Company, :id => "1")
  controller.should_receive(:current_company).and_return(company)
  get :new
end

这是我对员工控制器的新操作

  def new
    @staff = Staff.new
    @staff.company_id = current_company.id
  end

我总是出错

Failure/Error: get :new
     NameError:
       undefined local variable or method `current_company' for #<StaffsController:0x000000028d6ad8>

我也尝试过将其存根而不是使用 should_receive

  controller.stub!(:current_company).and_return(company)

我得到同样的错误。

【问题讨论】:

  • current_company 在哪里定义?
  • 没有,这就是为什么我想把它存根。我将在 ApplicationController 中结束。如果我在我的 ApplicationController 中放置一个名为 current_company 的方法,错误就会消失,但是有没有办法将它存根以隔离我的控制器测试?
  • 您可以在您的测试中存根它,但如果它不存在,您不能尝试在您的应用程序代码中使用它。存根仅适用于您的测试类。
  • 好的,我应该先指定我的 ApplicationController,然后为 current_company 编写一个方法吗?
  • >> 如果它不存在,您不能尝试在应用程序代码中使用它

标签: ruby-on-rails session rspec stub


【解决方案1】:

您的代码对我来说看起来不错,它应该可以工作。一定还有其他我们没有看到的问题。我注意到控制器名称是“StaffsController”——对吗?仔细检查控制器的名称和相应的规范——它们应该是相同的。

【讨论】:

    【解决方案2】:

    我认为它在“应该成功”的示例/测试中被轰炸了,所以我把我的存根放在了 before 块中。

    require 'spec_helper'
    
    describe StaffsController do
    
      describe "GET 'new'" do
        let(:staff) { mock_model(Staff, :company_id= => nil)}
        let(:company) { mock_model(Company, :id => 1)}
    
        before do
          Staff.stub!(:new).and_return(staff)
          controller.stub!(:current_company).and_return(company)
        end
    
        it "should be successful" do
          get :new
          response.should be_success
        end
    
        it "should call current_company" do 
          controller.should_receive(:current_company).and_return(company)
          get :new
        end
      end
    end
    

    这适用于:

    class StaffsController < ApplicationController
      def new
        @staff = Staff.new
        current_company.id
      end
    end
    

    【讨论】:

    • new 操作到底应该做什么?来自current_company.id 的值没有分配给任何东西。
    • 啊这是我的下一个问题。我现在正在编写一个测试,将 current_company.id 分配给@staff.company_id,这样我就可以将它存储在表单中的隐藏字段中,这样它就会在创建员工时创建该链接(员工属于公司)。在评论中解释太混乱了,我想我可能会将其提取到另一个问题中。
    • @zeteic 我的下一个测试将是:it "should assign staff.company_id to 1" do staff.should_receive(:company_id=).with(1) get :new end
    猜你喜欢
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 2014-09-15
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多