habitations
Rspec vs js, let vs let
I love comparison pieces like Steve Hicks' article What JavaScript Tests Could Learn From RSpec that juxtapose the syntaxes, rules, shibboleths of two programming languages. Comprehension comes more quickly.
Interesting. In describing the perceived advantages of rspec’s let
method to declutter code, I noticed Hicks fails to mention this little maneuver he performs of encapsulating a result
function –result
and getResult
for rubes and javs respectively. It would seem this strategy is a given for him. But in my experience it’s one I’ve shied away from in JavaScript tests – especially any of non-trivial sophistication.
I prefer the subject invocation repeated in each it
block. I find this repetition comforting. Like:
describe("when the first value is negative", () => {
describe("when the second value is negative", () => {
it("returns a positive number", () => {
const second = -3;
const result = calculator.multiply(first, second)
expect(result).toEqual(3)
})
})
describe("when the second value is positive", () => {
it("returns a negative number", () => {
const second = 3;
const result = calculator.multiply(first, second)
expect(result).toEqual(-3)
})
})
})
Also, unlike what I’m doing above, Hicks is declaring the value of second
in beforeEach
blocks to hint at how more sophisticated JS tests would be written with heavier logic to execute before one or more test runs within the same scenario/context. In practice I find you often do both in JS tests – do preparation in before*
blocks and declare single-use constants within it
blocks (vs re-assigning/re-using).
Generally I keep re-assigning/re-using variables to a minimum if they can be localized – it is confusing to follow in JS. Beware of cross-contamination. Pollination. Sex.
But why: for some reason the concise syntax of let seems easier to track. Lack of curly braces?
This doesn’t really bother me though:
let sharedVar;
before(() => {
sharedVar = ...
})
describe(() => {
it(() => {
sharedVar = ...
})
})
Is rspec let
better than JS let
? Of course of course, it depends. le sigh
Even rspec maintainers caution us, as Hicks notes. Convenience always carries a caveat in programming. This is a substantial pillar of the “readability” discussion: durability of convenience.
Note: let can enhance readability when used sparingly (1,2, or maybe 3 declarations) in any given example group, but that can quickly degrade with overuse. YMMV.
Cool find: givens. Shoutout to the translators, the transcribers, the interpreters.
Wednesday October 25, 2023