2016-11-29 51 views
1

我是新来测试和挣扎的一些概念。我理解的想法是通过嘲弄和存根来隔离测试的东西,但是我用下面的挣扎:RSpec - 访问数组方法

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方法的行为吗?我感到困惑的确实是我正在测试的东西,通过对它进行测试,我基本上告诉测试代码做了什么,而不是测试代码本身?

如果有人能解释我是否理解这个错误,那么无论如何我可以重写测试或让它通过,这将不胜感激。

+0

'circle_id:circle_1.id' - 并且不需要存根'作业' –

+0

调用circle_1.jobs时返回该作业,它只是RSpec不知道如何从数组中调用'where'我可以看到 – Mark

+0

因为你存根它为阵,做什么我建议) –

回答

0

问题是,你将AR集合存入数组对象,当然这个方法没有where方法。

您想要在工厂级别建立关联。你可以用它来实现它

circle_id: circle_1.id # in job_1 

有了这个,你不必存根工作的集合,你的测试将按预期工作。

+0

我掐灭数组因为关联没有设置 - 但是正如你所解释的那样,从circle.jobs返回一个不同的对象。现在ID已经正确设置了,所有东西都在传递 - 感谢您的帮助。 – Mark

+0

@Mark确保接受答案(答案分数附近的复选标记),如果解决了问题。 –