Martini templates and tests

242 views Asked by At

I'm trying to split my application files from my testing files. It looks something like this:

main.go
views/
  layouts/
    layout.html
spec/
  main_test.go

main.go creates a Martini app and tells Martini.render where to look for the views:

func CreateApplication() {
  m := martini.Classic()
  m.Use(render.Renderer(render.Options{
    Directory: "views",
    Layout: "layouts/layout",
    Extensions: []string{".html"},
  }))
}

That all works really well when I'm using go run from the root folder. However, when I try to use the CreateApplication() function from the spec/main_test.go file, it's now looking for the views in spec/views because that's the run folder.

I went down the route of trying to use runtime.Caller() to get the absolute path, but that totally messes up when compilling the a binary.

I guess my question is how I can make this work? I want that CreateApplication() to work the same no matter where it was called from.

1

There are 1 answers

0
Kiril On

I often run into this problem. What I do in such cases, is to create a symlink from the child directory to the folder in the root directory which holds the templates. Up until now I haven't had any problems using this appraoch, but when an app goes to production I delete those symlinks. I actually have a script that creates the symlinks before I start testing, and then deletes them after I'm done.

In your case, it would look like this (I'm on Ubuntu or Cygwin):

main.go
views/
  layouts/
    layout.html
spec/
  main_test.go

$ cd spec
$ ln -s ../views views

main.go
views/
  layouts/
    layout.html
spec/
  main_test.go
  views <- this is the symlink

Now, when running your tests from spec/ the views directoy is found. I hope it helps you, and if my approach is somehow flawed, I'm eager to know!