Why we need test?
Know thy code. Make sure your code works as you expect.
The basic rule -- keep your test independent
Test should not depend on others. For example, the tested method should not depend on outer API call or another methods.
The TDD cycle
Red -> Green -> Refactor
Write test first, as there is no code, the test will fail.
Then try to add simplest code to let the test pass.
After let all tests passed, do refactor or add more tests.
How simple the code should be, in the second step? As simple as possible. Your code will evolve.
Just keep focus on current test, no need think ahead, as we will add more test.
No need try to write "good" code, we will do these in "Refactor" step.
"Baby step" is golden rule for writing code.
Core concepts
stub
How it works?
It change the code dynamic as you want.
For example, you have a method which needs call an API. You should "overwrite" the API method, let it return the result you want.
# suppose we use RSpec
def search(q)
GoogleApi.search(q)
end
expect(GoogleApi).to receive(:search).with("foo").and_return("Success")
expect(search("foo")).to eq("Success")
Factory
We should use factor such as FactorGirl creating objects.
checker(Midje) / matcher(RSpec)
A handy way to compare the actual result and expected result.
eg: eq
, be_close
, be_kand_of
before / setup
For setting up preconditions executed before each test.
before :each do
@movie = Movie.new(name: "my movie")
end
it "a dummy test" do
expect(@movie.name).to eq("my movie")
end
Benefits
- Testing >= Debug
When you debug the code will be throw away, but the test code will live forever. - Specific issues and Decomposition problem
- Move in small step
- Reflect and project your changing.