16
Root
28d

Mocking hardcoded data in frozen constants in Rails is such a fucking pain! Why must this be so difficult!?

asfdfakldsjfuck

Comments
  • 0
    That's what you get for hardcoding the data :) at least use a provider or repository pattern...

    Btw that's a problem I've found tdd eliminates completely
  • 1
    Yes, you're right, I know that there is this gem for it: minitest-stub-const.

    When I had to do this it was a constant used as a default value for an instance variable in the initialize method. So I created a reader for the instance variable then I stubbed the reader, not the constant.
  • 1
    Root!

    I was worried about you! Haven’t seen a rant in a while.
  • 2
    @netikras This is to store which images (logo sets) have been added to the project, their sizes, and their paths. As new sets can only be added via releases, hardcoding them in a constant seems better than storing them elsewhere, as it avoids disk and network access at the cost of a few kb of memory.

    As the constant grows I’m sure I’ll get annoyed and abstract it out somehow. That should make the specs will be easier to write.
  • 2
    @katbreitin Thanks 😊
    I haven’t had much to rant about. Not sure if that’s a good thing or not.
  • 0
    @Root repository doesn't mean you have to store data in another medium :)

    class MyRepo {
    public String getValue1() {return "aaa";}
    }

    class MyService {
    private MyRepo repo;
    constructor(MyRepo repo) {this.repo = repo;}

    // take data from the repo rather than hardcode it in the interactor
    // inject mocked repo as you need it
  • 2
    @netikras I will likely end up doing something similar. The accepted pattern in this codebase is constants, however, so I’m sure I’ll catch some flak for bucking it. 🤦🏻‍♀️
  • 0
    @Root still counts as constants ;) indirectly accessible, but constants.

    Inline constants is a terrible idea imo. Ir makes the codebase rigid and untestable [and non-mockable]. And violates the sOlid. So if you get heated for this you've got plenty of arguments up your sleeve.
  • 1
    @netikras Ahh, we’re not using inline constants — I can’t imagine anyone has a good argument for using those. They’re all class constants.

    But in this case it’s a lot of data in a single constant (a hash of hashes), rather than an individual constant per set, and that is what’s causing the mocking difficulty.
Add Comment