[英]How to call a method from Application Controller in any given controller test
I have a controller that POSTs a new instance of a model into a database after the user fills out a form. 我有一个控制器,可以在用户填写表格后将模型的新实例发布到数据库中。 This form is created using an
each do
that loops over a series of inventory
items defined in the Application Controller. 使用循环在Application Controller中定义的一系列
inventory
项目的each do
创建此表单。
In other words, this is the view code: 换句话说,这是视图代码:
<%= form_for @requestrecord, :html=> {:id => 'form'} do |f| %>
<div class="col-xs-12">
<p><b>Items we have available</b></p>
</div>
<% @inventory.each do |category, list| %>
<div class="col-xs-2">
<div class="form-group box">
<h5> <%="#{category}"%> </h5>
<% list.each do |thing| %>
<%= f.check_box(:items, {:multiple => true}, "#{thing}") %>
<%= f.label(:items, "#{thing}") %>
</br>
<% end %>
</div>
</div>
<% end %>
There is a method in the application controller that defines inventory: 应用程序控制器中有一种定义清单的方法:
def inventory
@inventory = { some hash }
end
And then this method is called in the Requests controller that I'm trying to test: 然后在我要测试的Requests控制器中调用此方法:
def create
inventory
@requestrecord = Request.new(request_params)
end
The problem is in my Rspec controller test, I now have to manually define this inventory
again like so: 问题出在我的Rspec控制器测试中,现在我必须再次手动定义此
inventory
,如下所示:
before do
@inventory = { some hash }
end
Instead of doing this, is there a way to call the method from the Application Controller in the before
statement? 除了这样做,还有没有办法在
before
语句中从Application Controller调用该方法? The @inventory
is a rather long hash... @inventory
是一个相当长的哈希...
Thanks! 谢谢!
You can access your controller in rspec with 'controller', so 您可以使用'controller'访问rspec中的控制器,因此
before do
@inventory = controller.inventory
end
should do the job! 应该做的工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.