【问题标题】:RSpec - accessing array methodsRSpec - 访问数组方法
【发布时间】:2016-11-30 00:30:45
【问题描述】:

我不熟悉测试和一些概念。我理解这个想法是通过模拟和存根单独测试事物,但是我正在努力解决以下问题:

class Circle
  has_many :jobs

  def accepted
    jobs.where('sitter_id > 0')
  end
end

class Job
  belongs_to :circle
end

还有我的 RSpec:

require 'rails_helper'

RSpec.describe Circle, type: :model, focus: true do

  let (:circle_1) { FactoryGirl.create(:circle, title: 'London',
                                                location: 'London',
                                                administrator_id: 1) }

  let (:job_1) { FactoryGirl.create(:job, start_time: "2016-11-14 20:00:00",
                                          end_time: "2016-11-14 23:00:00",
                                          tokens_offered: 6,
                                          requester_id: 1,
                                          circle_id: 1,
                                          sitter_id: 5,
                                          actual_start_time: "2016-11-14 20:00:00",
                                          actual_end_time: "2016-11-14 23:30:00",
                                          tokens_paid: 7) }

  before do
    circle_1.stub(:jobs).and_return([job_1])
  end

  describe 'instance methods' do
    context 'accepted' do 
      it 'should return jobs with a sitter' do 
        expect(circle_1.accepted).to include(job_1)
      end
    end
  end
end

这会导致:

NoMethodError:
   undefined method `where' for #<Array:0x007feb4ae72858>

然后我会在数组上存根 where 方法的行为吗?我感到困惑的是,这肯定正是我正在测试的内容,通过存根它,我基本上是在告诉测试代码做了什么,而不是测试代码本身?

如果有人能解释我是否理解错误,以及我如何重写测试或让它通过,将不胜感激。

【问题讨论】:

  • circle_id: circle_1.id - 并且不需要存根jobs
  • 调用circle_1.jobs时返回作业,只是RSpec不知道如何从我看到的数组中调用'where'
  • 因为你将它作为数组存根,所以按照我的建议做 ;)
  • 我来这里寻求帮助,然后在得到帮助时争论 :D 你完全正确,谢谢你的帮助

标签: ruby-on-rails rspec


【解决方案1】:

问题在于您将 AR 集合存根到一个数组对象中,而该数组对象当然没有 where 方法。

您想在工厂级别建立关联。您可以通过

circle_id: circle_1.id # in job_1

有了这个,您就不必存根作业集合,并且您的测试将按预期工作。

【讨论】:

  • 我对数组进行了存根,因为没有设置关联 - 但是正如您所解释的那样,它从 circle.jobs 返回一个不同的对象。现在 ID 已正确设置,一切顺利 - 感谢您的帮助。
  • @Mark 如果解决了问题,请确保接受答案(答案分数附近的复选标记)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多