我在下面创建了 RSpec 测试。我试着打subject了几次电话。但我无法得到预期的结果。我打subject了三遍,不是吗?所以,我希望有三个 Book 记录。难道subject不能叫一个时间?
require 'rails_helper'
RSpec.describe Book, type: :model do
context 'some context' do
subject { Book.create }
before do
subject
end
it 'something happen' do
subject
expect { subject }.to change{ Book.count }.from(0).to(3)
end
end
end
Run Code Online (Sandbox Code Playgroud)
Grz*_*orz 13
不。let并且subject被记忆(和延迟加载)。
你可以像这样改变它
subject { 3.times { Book.create } }
it 'something happen' do
expect { subject }.to change{ Book.count }.from(0).to(3)
end
Run Code Online (Sandbox Code Playgroud)
或者,如果您(无论出于何种原因)想要调用 3 次 - 定义一个方法:
subject { create_book }
def create_book
Book.create
end
before do
create_book
end
it 'something happen' do
create_book
expect { subject }.to change{ Book.count }.from(2).to(3)
end
Run Code Online (Sandbox Code Playgroud)
然后它将被调用 3 次:一次在 before 块中,一次在期望之前,一次在期望中(但变化将来自2not from 0,因为这 2 次是在之前被调用的)
如果你不想记住结果,你也可以使用 Proc
describe MyClass do
let(:param_1) { 'some memoized string' }
let(:described_method) { Proc.new { described_class.do_something(param_1) } }
it 'can run the method twice without memoization' do
expect(described_method.call).to have_key(:success) # => {success: true}
expect(described_method.call).to have_key(:error) # => {error: 'cant call do_something with same param twice'}
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4484 次 |
| 最近记录: |