Ruby-on-rails 如何测试也定义为辅助方法的 ApplicationController 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4739116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to test ApplicationController method defined also as a helper method?
提问by Mirko
In my ApplicationController I have a method defined as a helper method:
在我的 ApplicationController 中,我有一个方法定义为辅助方法:
helper_method :some_method_here
helper_method :some_method_here
- How do I test ApplicationController in RSpec at all?
- How do I include/call this helper method when testing my views/helpers?
- 我如何在 RSpec 中测试 ApplicationController?
- 在测试我的视图/助手时如何包含/调用这个助手方法?
I'm using Rails3 with RSpec2
我在 RSpec2 中使用 Rails3
回答by Jimmy Cuadra
You can use an anonymous controllerto test your ApplicationController, as describe in the RSpec documentation. There's also a section on testing helpers.
您可以使用匿名控制器来测试您的 ApplicationController,如 RSpec 文档中所述。还有一个关于测试助手的部分。
回答by Konrad Reiche
You can invoke your helper methods on subjector @controllerin the specification.
您可以在规范中subject或@controller规范中调用您的辅助方法。
I have been looking for a solution to this problem and anonymous controller was not what I was looking for. Let's say you have a controller living at app/controllers/application_controller.rbwith a simple method which is not bound to a REST path:
我一直在寻找这个问题的解决方案,而匿名控制器并不是我想要的。假设您有一个app/controllers/application_controller.rb使用简单方法的控制器,该方法未绑定到 REST 路径:
class ApplicationController < ActionController:Base
def your_helper_method
return 'a_helpful_string'
end
end
Then you can write your test in spec/controllers/application_controller_spec.rbas follows:
然后您可以spec/controllers/application_controller_spec.rb按如下方式编写测试:
require 'spec_helper'
describe ApplicationController do
describe "#your_helper_method" do
it "returns a helpful string" do
expect(subject.your_helper_method).to eq("a_helpful_string")
end
end
end
While @controllerand subjectcan be used interchangeable here, I would go for subjectas its the RSpec idiomatic way for now.
虽然@controller和subject在这里可以互换使用,但我现在将subject其作为 RSpec 惯用方式。

