简体   繁体   English

在 Rails 5+ 中使用 RSpec 时,我应该用什么来代替“赋值”?

[英]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 rails-controller-testings - 分配

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:因此,例如,如果您在请求规范中测试 API,您可以在响应正文中测试解析的 json:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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