RSpec 和 FactoryGirl
RSpec and FactoryGirl
我目前有一个 RSpec 测试:
Rspec.describe Some::ServiceClass do
args = ['1', '2']
subject { described_class.new(args) }
describe '#finder_method' do
let(:user_1) { FactorGirl.create(:user) }
it 'returns the right number of users' do
expect(subject.finder_method.count).to eq(1)
end
end
end
这就是被测 class 的样子
module Some
class Service
....
# other methods used to identify the resource model
def finder_method
resource.all
end
end
end
预期:
- 当调用
resource.all
时,我预计
let(:user_1) FactoryGirl.create(:user)
,在规范测试中,将在 users
table(测试环境) 中填充 1 行
- 因此,当
subject.finder_method
被评估时,它将 return 一个 AR 对象。
实际结果:
- 而不是
subject.finder_method
,它只是在 AR 对象上调用 all
,returns #<ActiveRecord::Relation []>
谁能解释一下为什么会这样? FactoryGirl 创建的 user_1
在哪里?
呃!!
let
是罪魁祸首......完全忘记了它被懒惰地评估。我需要睡一觉:(
我目前有一个 RSpec 测试:
Rspec.describe Some::ServiceClass do
args = ['1', '2']
subject { described_class.new(args) }
describe '#finder_method' do
let(:user_1) { FactorGirl.create(:user) }
it 'returns the right number of users' do
expect(subject.finder_method.count).to eq(1)
end
end
end
这就是被测 class 的样子
module Some
class Service
....
# other methods used to identify the resource model
def finder_method
resource.all
end
end
end
预期:
- 当调用
resource.all
时,我预计 let(:user_1) FactoryGirl.create(:user)
,在规范测试中,将在users
table(测试环境) 中填充 1 行
- 因此,当
subject.finder_method
被评估时,它将 return 一个 AR 对象。
实际结果:
- 而不是
subject.finder_method
,它只是在 AR 对象上调用all
,returns#<ActiveRecord::Relation []>
谁能解释一下为什么会这样? FactoryGirl 创建的 user_1
在哪里?
呃!!
let
是罪魁祸首......完全忘记了它被懒惰地评估。我需要睡一觉:(