开发者

How do I determine the default action for a Rails controller?

I'm working on a functional test that needs to assert that a certain XHTML tag is present in a certain set of controllers. I'm basically doing this:

class ApplicationControllerTest < ActionController::TestCase
  def setup
    @controller 开发者_C百科= ApplicationController.new
  end
  # [...]
  def test_foo_bar_and_baz_include_stylesheet
    [FooController, BarController, BazController].each do |controller|
      @controller = controller.new
      get :show
      assert_select 'head > link[rel="stylesheet"]'
    end
  end
end

The problem is that not all controllers have a :show action. What I need to do is ask either the controller or the routing configuration for the controller's default action and call get with that.

Update: Joseph Silvashy was right: I ended up separating my controller gets out into separate test cases. Solving the "default" route problem was bad enough, until I discovered that some of my routes had conditions attached, and I would have to parse them to craft the correct get call. And finally, Rails functional tests don't deal very well with calling get multiple times in the same test case, especially when that those calls are hitting multiple controllers. :(

I think the lesson here is one that we all know by heart but sometimes is hard to accept: if the code looks hairy, you're probably doing it wrong. ;)


Controllers don't have a "default" view or action, additionally actions can be named anything you want, they don't have to be the standard index, show, new, etc...

I'll probably have to :get the appropriate action for each controller you want to test. It's likely each test will be different down the road anyhow, even though right now they all have the same requirement, I think it makes sense to write one for each action regardless.


try to use the respond_to function: http://www.ruby-doc.org/core/classes/Object.html#M001005 to check if a method exitst.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜