简体   繁体   中英

What should I use in place of “assigns” when using RSpec with Rails 5+?

I'm currently testing the index action of one my controllers in the form of a request spec and want to make sure that the object collection is being passed through. So far I've consulted this post for guidance:

it "populates an array of contacts starting with the letter" do
  smith = FactoryBot.create(:contact, lastname: 'Smith')
  jones = FactoryBot.create(:contact, lastname: 'Jones')
  get :index, letter: 'S'
  expect(assigns(:contacts)).to match_array([smith])
end

Unfortunately the above example will thrown this error:

NoMethodError: assigns has been extracted to a gem. To continue using it, add `gem 'rails-controller-testing'` to your Gemfile.

I'd simple like to know what I would use in favor of assign in this case? I've looked high and low for an example for this new methodology but came up short.

Reference

rails-controller-testings - assigns

Just test the output of the controller instead of poking your fingers into the internals. Better yet don't use controller specs - use request or feature specs instead.

The output of the controller is the response object which contains headers and the response body.

So for example if you're testing an API in a request spec you could test the parsed json in the response body:

it "returns an array of contacts starting with the letter" do
  smith = FactoryBot.create(:contact, lastname: 'Smith')
  jones = FactoryBot.create(:contact, lastname: 'Jones')
  get :index, letter: 'S'
  last_names = parsed_response["contacts"].map { |c| c["lastname"] }
  expect(last_names).to include 'Smith'
  expect(last_names).to_not include 'Jones'
end

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