RSPEC如何让和出租!更换原始参数?
在RSPEC中编写测试的过程中,如果您遇到重复必需的参数{...},则可以使用让
编写它。这避免了为每个示例提前编写一堆参数准备。
但是,我不太了解更好规格的范式。他的原始代码是这样:
describe '#type_id' do
before { @resource = FactoryBot.create :device }
before { @type = Type.find @resource.type_id }
it 'sets the type_id field' do
expect(@resource.type_id).to eq(@type.id)
end
end
使用让它成为以下内容后,
describe '#type_id' do
let(:resource) { FactoryBot.create :device }
let(:type) { Type.find resource.type_id }
it 'sets the type_id field' do
expect(resource.type_id).to eq(type.id)
end
end
调用资源
几乎相同的方法,使用LET的好处是什么? factorybot.create:设备
的功能是什么?而且我看不到type
在哪里调用?
In the process of writing tests in Rspec, if you encounter repeated required parameters {...}, you can use let
to write it. This avoids writing a bunch of parameter preparations in advance for each example.
However, I don't quite understand the paradigm of Better Specs. His original code is this:
describe '#type_id' do
before { @resource = FactoryBot.create :device }
before { @type = Type.find @resource.type_id }
it 'sets the type_id field' do
expect(@resource.type_id).to eq(@type.id)
end
end
After using let it becomes the following
describe '#type_id' do
let(:resource) { FactoryBot.create :device }
let(:type) { Type.find resource.type_id }
it 'sets the type_id field' do
expect(resource.type_id).to eq(type.id)
end
end
It looks like the way to call a resource
is pretty much the same, what's the benefit of using let ? What is the function of FactoryBot.create:device
? And I can't see where type
is being called?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不同之处在于,让我们懒洋洋评估,然后在规格的其余部分进行回忆。
因此,在第一个示例中,首先,以前的块运行并设置@Resource和@Type的值,然后规格运行。
在第二个示例中,规格运行,当它引用“资源”时,让块运行并返回一个值,然后在引用“类型”时,将运行let block。类型本身引用“资源”的LET块,因此它获取了从首次参考资源回忆的资源的值。
就其价值而言,我不同意让我们“更好”。我和我的团队发现,他们所做的就是使规格更难理解,而几乎没有利益,我们在所有项目中都删除了它们的所有使用。
实际上,我认为大多数“更好的规格”实际上是糟糕的建议,因此,如果您努力理解为什么某事“更好”,那么您并不孤单:)
The difference is that lets are lazily evaluated and then memoized for the rest of the spec.
So in the first example, first the before blocks run and set the values of @resource and @type, and then the spec runs.
In the second example, the spec runs and when it references 'resource' the let block runs and returns a value, then when 'type' is referenced is runs the let block for that. The let block for type itself references 'resource' so it gets the value for resource that was memoized from the first time resource was referenced.
For what its worth, I disagree that lets are 'better'. My team and I have found that all they do is make specs much harder to understand for very little benefit, and we have removed all use of them in all our projects.
In fact, I consider that most of 'better specs' is actually poor advice, so if you are struggling to understand why something is 'better', you are very much not alone :)