简体   繁体   中英

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.

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:

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:

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? The @inventory is a rather long hash...

Thanks!

You can access your controller in rspec with 'controller', so

before do
  @inventory = controller.inventory
end

should do the job!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM