How testing an url with params in Cuba?

243 Views Asked by At

Following the example on https://github.com/soveran/cuba#usage and changing it a little:

Cuba.define do
  on get do
    on 'home' do
      res.write "Aloha!"
    end
  end
  on 'api' do
    on get do
      on "home", params("a"), param("b") do |a,b|
        res.write "Hello World!"
      end
    end
  end
end

Test:

scope do
  test "Homepage" do
    get "/api/home?a=00&b=11"
    assert_equal "Hello World!", last_response.body
  end
end

But I get an Assertion Failed:

AppTest.rb:15:in `block (2 levels) in <main>': "Hello world!" != "" (Cutest::AssertionFailed)

It is like that the url which I use in the test is not right. How should I change it?

Update:

I noticed that if I change the definition then it works correctly:

Cuba.define do
  on 'api' do
    on get do
      on "home", params("a"), param("b") do |a,b|
        res.write "Hello World!"
      end
    end
  end
  on get do
    on 'home' do
      res.write "Aloha!"
    end
  end
end
1

There are 1 best solutions below

0
djanowski On

I would suggest you structure your routes in a different way to keep things clean and maintainable.

For instance, you could do:

class API < Cuba
  on get, root do
    res.write("foo")
  end
end

class Web < Cuba
  on get, "home" do
    res.write("bar")
  end
end

Cuba.define do
  on "api" do
    run API
  end

  on default do
    run Web
  end
end

Also, remember that when you use the param matcher you're saying that the param must be there for the route to match. Sometimes this is what you want. However, if the query parameter is optional, you would access it through req:

on get, "home" do
  foo = req.GET["foo"]

  res.write(foo)
end