Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
From the author of Writing Your First Test

Writing Your First Test

To test that this setup works the way we expect, let's write a simple class and a test for it.

In app/assets/javascripts, create a new file called greeter.js.coffee. In that file, let's create a class called Greeter that has a function sayHello. The sayHello function will take a name argument and respond with a string that greets that name.

# app/assets/javascripts/greeter.js.coffee
class @Greeter

  sayHello: (name) ->
    "Hello #{name}!"

Now let's create a simple test to assert that sayHello does what we expect it to do. By default, Konacha expects all tests to be in the spec/javascripts folder. (This can be reconfigured if you prefer a different location.) The default location works just fine for me. In the spec/javascripts directory (you'll probably need to create these folders), create a new file called greeter_spec.js.coffee. Another default of Konacha is that tests must end with _spec. This requirement follows the RSpec style of determining what is or isn't a test.

# spec/javascripts/greeter_spec.js.coffee
#= require application

describe "Greeter", ->

  it "says hello", ->
    greeter = new Greeter()
    greeter.sayHello("Mark").should.eql("Hello Mark!")

If you've seen or written RSpec tests, this test should be fairly familiar. If not, the gist of what's happening is that we're requiring the application.js file from the asset pipeline, which by default includes our greeter.js.coffee file. It then sets up a test and asserts that the sayHello function behaves correctly.

  • + Share This
  • 🔖 Save To Your Account