【问题标题】:Exceedingly strange ruby '||=' and rspec doubles behavior非常奇怪的 ruby​​ '||=' 和 rspec 使行为加倍
【发布时间】:2014-02-20 23:12:58
【问题描述】:

运行以下rspec gem 版本:

  * rspec (2.14.1)
  * rspec-core (2.14.7)
  * rspec-expectations (2.14.5)
  * rspec-mocks (2.14.6)
  * rspec-rails (2.14.1)

还有octokit 2.7.1

鉴于spec/support/octokit.rb中的以下内容:

# This support package contains modules for octokit mocking

module OctokitHelper
  def mock_pull_requests_for_org org
     mock_org_repos(org).map do |repo| 
      mock_pull_requests repo 
    end.flatten
  end
  def mock_org_repos org
    @@repos ||= [
      double('Sawyer::Resource', name: 'repo 1'),
      double('Sawyer::Resource', name: 'repo 2')
    ]
    Octokit.stub(:org_repos) { |org=org| @@repos }
    @@repos
  end
  def mock_pull_requests repo, gh_handle=nil
    @@pulls ||= [
      double('Sawyer::Resource', title: 'pr 1'),
      double('Sawyer::Resource', title: 'pr 2')
    ]
    Octokit.stub(:pull_requests) { |repo| @@pulls }
    @@pulls 
  end
end

RSpec.configure do |config|
  config.include OctokitHelper 
end

每当我第一次尝试从规范调用mock_org_repos 时,@@repos.first.name 就是repo 1。第二次,@@repos.first.name 抛出了一个非常奇怪的错误:

  1) StudentsController GET #submissions renders pull requests template
     Failure/Error: get :submissions, student_id: 2
       Double "Sawyer::Resource" received unexpected message :name with (no args)

我使用mock_org_repos的一个例子:

require 'spec_helper'

describe StudentsController do
  describe 'GET #submissions' do
    before do
      @user = FactoryGirl.create(:instructor)
      @user.stub(:is_instructor?) { true }
      @submissions = mock_pull_requests_for_org ENV['GA_ORG_NAME']
      controller.stub(:current_user) { @user }
      get :submissions, student_id: 2
    end
    it 'assigns @submissions' do
      assigns(:submissions).should == @submissions
    end
    it 'renders pull requests template' do
      response.should render_template 'submissions'
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby rspec octokit


    【解决方案1】:

    我的猜测是,您在mock_pull_requests 中创建的同名双打之一正在发送:name,但您可以通过确保您的双打具有唯一名称来检查这一点(即 @ 的第一个参数987654323@)。

    【讨论】:

      【解决方案2】:

      非常感谢rsofaer 借给我第二双眼睛来解决这个问题,我想指出现在非常非常明显的问题:

      当通过类变量引用存根时,每次运行示例时都会“清除”在双精度上存根的方法。

      This 非常清楚地解释了 RSpec 如何在幕后工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-08
        • 2013-11-15
        • 2016-03-13
        • 2011-03-01
        • 2015-11-17
        • 2012-12-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多