更新时间:2021-11-10 22:26:05
你不应该在 it
、specify
、 之外创建和操作它们before
、let
和 subject
块.否则在测试后不会重置主题和其他变量.
You shouldn't be creating instances and manipulating them outside of it
, specify
, before
, let
, and subject
blocks. Otherwise the subject and other variables are not reset after a test.
下面我使用几种不同的样式重写了您的规范.请参阅内嵌注释以获取解释.
Below I rewrote your spec using a couple of different styles. See the inline comments for an explanation.
class Tmp
# Exposes the @values ivar through #values
attr_reader :values
def initialize
@values = {}
end
def modify(new_value1, new_value2)
@values = {a: new_value1, b: new_value2}
end
end
describe Tmp do
#`let` makes the return value of the block available as a variable named `instance` (technically it is a method named instance, but let's call it a variable).
let(:instance) { described_class.new }
# Inside an it block you can access the variables defined through let.
it 'should be modifiable' do
instance.modify('hi', 'bye')
instance.values.should == {a: 'hi', b: 'bye'}
end
# or
# `specify` is like `it` but it takes no argument:
specify do
instance.modify('hi', 'bye')
instance.values.should == {a: 'hi', b: 'bye'}
end
# or
# This is another common way of defining specs, one describe per method.
describe '#modify' do
let(:instance) { described_class.new }
# Here we define the subject which is used implicitly when calling `#should` directly.
subject { instance.values }
before { instance.modify('hi', 'bye') }
it { should == {a: 'hi', b: 'bye' } # Equivalent to calling `subject.should == ...`
end
# or
# When we don't specify a subject, it will be an instance of the top level described object (Tmp).
describe '#modify' do
before { subject.modify('hi', 'bye') }
its(:values) { should == {a: 'hi', b: 'bye' }
end
end