rspec - what is the syntax of before :each and before :all vs let! and let
문제
When can I use let or let! and how can I then refer to variables inside the test?
How does the usage of let and let! compare to using before :each and before :all?
해결책
The 'classic' way of using before(:each)
and before(:all)
is
describe "tests" do
before :each do
@var1='a'
@var2='b'
end
end
You then refer to the instance variables by preceeding them with an @
sign inside the tests, i.e.
describe "tests" do
before :each do
@var1='a'
@var2='b'
end
it "does stuff" do
a=some_class.some_method(@var1)
expect(a).to eq @var2
end
end
If you want a variable to have the same value in each test you can use before :all
.
If you want a variable to have the same value generated for each test use before :each
.
Generally use before :each
as improper use of before :all
can too easily lead to intermittent test failures.
Think of before :all
as defining constants.
The let
/let!
format looks like this:
describe "tests" do
let(:var1) {'a'}
let!(:var2) {srand(25)}
it "does stuff" do
a=some_class.some_method(var1)
expect(a).to eq var2
end
end
Notice several things:
var1
andvar2
now look like local variables, i.e.var1
instead of@var1
when used in the test and setup. In actual fact they are test class methods. The important thing to note for usage is that you do NOT use the@
sign when subsequently using them unlike the before:each
andbefore :all
where you did.- In the first case of the
let
's example,let
is used withvar1
. This allow the memoization across examples to work. In the second caselet!
is used withvar2
. This is needed because you want the variable (method) to be called/set explicitly before each use.srand()
is a great example of when you would need this as it seeds the random number generator but only for the next use ofrand()
so if using it in multiple test examples resetting it is needed each time.
제휴하지 않습니다 StackOverflow