我的问题很大程度上是通过标题来解释的。我试着在谷歌上搜索,但没有找到任何令人满意的东西。rubocop-rspec does not allow expect inside before,为什么?有没有一个好的理由来避免这样的用法?感谢您的提前解释!
发布于 2019-03-01 21:57:05
Four phase test是一种通常用于单元测试的测试模式。它的一般形式:
test do
setup
exercise
verify
teardown
endbefore是setup阶段的一部分,开发人员在该阶段创建场景和支持数据。
expect是verify阶段的一部分,该阶段发生在it块中。
例如,一种常见的模式是在before块中使用allow,在it块中使用expect。
RSpec.describe User do
describe '#forgot_password' do
before { allow(EmailService).to receive(:send) }
subject { FactoryBot.create(:user).forgot_password }
it 'sends an email to user to start the password resetting process' do
subject
expect(EmailService).to have_received(:send).with(...)
end
end
end还可以在应用程序的其他层(spec_helper.rb,共享示例)中添加before块,人们不希望为了测试成功而依赖于before块的正确顺序。
发布于 2019-02-28 18:42:46
只有测试应该包含期望(也称为断言)。before块用于配置运行测试的环境。它们本身并不意味着是测试。
发布于 2019-11-20 18:37:06
我同意before过滤器中的期望,因为您在示例中没有改变任何东西,您总是在测试常规设置,但是在after过滤器中,我没有看到避免期望的理由。
在编写测试时,上下文是最重要的,您在不同的参数(或上下文)下测试相同的代码,因此,示例只需要修改上下文,断言可以保持不变。
请参阅此示例:
RSpec.describe Foo do
subject { create(:foo) }
describe 'some_method' do
let(:foo) { create(:foo) }
after do
foo.update_rate
subject.update_rate
expect(foo.rate).to be > subject.rate
end
it 'gives higher rates to foos with more reviews if all are positive' do
foo.update!(votes_up_count: 10, reviews_count: 10)
subject.update!(votes_up_count: 1, reviews_count: 1)
end
it 'gives higher rates to foos with less positive reviews and no negative reviews' do
foo.update!(votes_up_count: 4, reviews_count: 4)
subject.update!(votes_up_count: 5, reviews_count: 6)
end
end
end而不是
RSpec.describe Foo do
subject { create(:foo) }
describe 'some_method' do
let(:foo) { create(:foo) }
it 'gives higher rates to foos with more reviews if all are positive' do
foo.update!(votes_up_count: 10, reviews_count: 10)
subject.update!(votes_up_count: 1, reviews_count: 1)
foo.update_rate
subject.update_rate
expect(foo.rate).to be > subject.rate
end
it 'gives higher rates to foos with less positive reviews and no negative reviews' do
foo.update!(votes_up_count: 4, reviews_count: 4)
subject.update!(votes_up_count: 5, reviews_count: 6)
foo.update_rate
subject.update_rate
expect(foo.rate).to be > subject.rate
end
end
end所以老实说,我不会把这个警察当做福音,我认为它违背了良好的测试实践。
https://stackoverflow.com/questions/54807896
复制相似问题