pointfreeco / swift-snapshot-testing

📸 Delightful Swift snapshot testing.
https://www.pointfree.co/episodes/ep41-a-tour-of-snapshot-testing
MIT License
3.74k stars 568 forks source link

Snapshot save location as an Environment Variable #399

Open cjrieck opened 3 years ago

cjrieck commented 3 years ago

I first wanted to say thank you for the amazing library! We love using it in our project 😃

We want to utilize Test Plans to test our app against English and Spanish locales. We have snapshots recorded for the English variant of our app, but were unclear about how we can save Spanish snapshots side-by-side with our existing snapshots.

A solution that came to mind was, much like how we can alter the destination of snapshot diffs via the SNAPSHOT_ARTIFACTS env variable, we can allow a user to define an environment variable for the destination of the recorded snapshots. This would allow us to declare something like

// English Test Plan Configuration
SNAPSHOTS_DIR="__English_Snapshots__"

// Spanish Test Plan Configuration
SNAPSHOTS_DIR="__Spanish_Snapshots__"

and allow us to assert against the appropriate snapshots per test plan configuration.

I was wondering if this has already been discussed and is documented somewhere or if this would be a new feature altogether.

cjrieck commented 3 years ago

It looks like I may have spoke too soon. There's already a PR open with the aforementioned functionality to support Test Plans

CodeStage commented 3 years ago

It would be a nice addition to the framework, we have solved this by adding the localizations as test plan configurations and then using a helper:

import Cocoa
import SnapshotTesting

extension NSView {
    func setFittingSize() -> Self {
        frame = NSRect(x: 0,
                       y: 0,
                       width: fittingSize.width,
                       height: fittingSize.height)
        return self
    }

    func snapshotTestWithLocale(fittingSize: Bool = true,
                                file: StaticString = #file,
                                testName: String = #function,
                                line: UInt = #line,
                                embedInWindow: Bool = true)
    {
        if embedInWindow {
            let viewController = NSViewController()
            viewController.view = self
            _ = NSWindow(contentViewController: viewController)
        }
        assertSnapshot(matching: fittingSize ? setFittingSize() : self,
                       as: .imageWithLocale,
                       file: file,
                       testName: testName,
                       line: line)
    }
}

extension Snapshotting where Value == NSView, Format == NSImage {
    static var imageWithLocale: Snapshotting {
        var image: Snapshotting<NSView, NSImage> = .image
        image.pathExtension = Locale.current.identifier + ".png"
        return image
    }
}