0

I'm using Rails 5.2 with rspec-rails 3.7 and rails-controller-testing gems. I have a controller that filters results on the index action (yeah, bad practice, legacy code, etc). The problem is I need to test that when I do GET work_orders/index params: { keywords: 'some word' }, the instance variable @work_orders returns filtered results, but if I use assigns(:work_orders) it returns nil. I even tested this assigning the last WorkOrder to that variable, but it still doesn't show the variable in the hash.

work_orders_controller.rb

def index
  ... some code ...
  @work_orders = WorkOrder.last
  respond_to do |format|
      format.html
  end
end

spec/controllers/work_orders_controller_spec.rb

require 'rails_helper'

describe WorkOrdersController do
  describe 'GET index' do
    it 'collects work orders filtered by courier_ot in @work_orders' do
      get :index
      expect(assigns(:work_orders)).to be_an_instance_of WorkOrder
    end
  end
end

That is the simplest example I tested and it doesn't work. The assigns call returns nil, and if I use byebug to inspect the hash, it only has this: {"marked_for_same_origin_verification"=>true}.

The real test should use get :index, params: { keywords: 'asdf' } and test that it gets the filtered work orders.

Any help would be appreciated. Thanks.

sbstnssndn
  • 145
  • 1
  • 18
  • Have you actually created any WorkOrder rows in the DB? Because if you didn't `WorkOrder.last` should actually be `nil`. – Sam Figueroa Jul 07 '20 at 06:41
  • I thought I did. I dumped my development data into test, but I think it gets deleted after I run RSpec. Also, it doesn't seem to create the things I create in seed.rb. I think I don't understand how that works. Where should I create the testing data to be able to use it in tests? – sbstnssndn Jul 07 '20 at 15:35
  • Normally testing setups wipe most of everything before every test is run. Every test needs to setup its own data. This keeps side effects low. A work config row needs to exist before you run `get :index` you could put code that creates it right before that line. That is run `WorkOrder.create` as the first line of the `it` block. (You might need more attributes for create to satisfy any validations you have set). Also look up the documentation on `let` and `let!` for RSpec, it's the more usual way to add test data. – Sam Figueroa Jul 28 '20 at 05:10

0 Answers0