简体   繁体   English

rspec中的assigns是什么意思

[英]What does assigns mean in rspec

What does that line of code do?那行代码有什么作用?

assigns(:articles).should eq([article])

in the following rspec在以下 rspec

  describe "GET #index" do
    it "populates an array of articles" do
      article = Factory(:article)
      get :index
      assigns(:articles).should eq([article])
    end

    it "renders the :index view" do
      get :index
      response.should render_template :index
    end
  end

assigns relates to the instance variables created within a controller action (and assigned to the view). assigns与在控制器操作中创建的实例变量相关(并分配给视图)。


to answer your remark in comments, I guess that:要在评论中回答您的评论,我想:

  • 1) your index action looks like @articles = Articles.all (I hope you use pagination though) 1)您的索引操作看起来像@articles = Articles.all (但我希望您使用分页)

  • 2) prior to the spec block above, you have one article created in db (or I hope you stub db queries in db) 2)在上面的规范块之前,您在 db 中创建了一篇文章(或者我希望您在 db 中存根 db 查询)

  • 1 + 2 => @articles should contain one article, that's your spec expectation 1 + 2 => @articles应该包含一篇文章,这是您的规范期望

In a controller spec, assigns will take a symbol (eg assigns(:variable) ) and returns the controller's corresponding instance variable (eg @variable in the controller).在控制器规范中, assigns将采用一个符号(例如@variable assigns(:variable) )并返回控制器对应的实例变量(例如控制器中的 @variable)。

So in the question's example, the index method of the controller evidently sets @articles to a list of articles, and assigns merely makes that value available in the spec.因此,在问题的示例中,控制器的 index 方法显然将@articles设置为文章列表,而assigns仅使该值在规范中可用。

assigns has been moved into a gem: https://github.com/rails/rails-controller-testing . assigns已移至 gem 中: https ://github.com/rails/rails-controller-testing。

https://joshfrankel.me/blog/accessing-instance-variables-within-a-rspec-controller-test/ https://joshfrankel.me/blog/accessing-instance-variables-within-a-rspec-controller-test/

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

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