26

What does that line of code do?

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

in the following 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
Aydar Omurbekov
  • 2,047
  • 4
  • 27
  • 53

2 Answers2

29

assigns relates to the instance variables created within a controller action (and assigned to the view).


to answer your remark in comments, I guess that:

  • 1) your index action looks like @articles = Articles.all (I hope you use pagination though)

  • 2) prior to the spec block above, you have one article created in db (or I hope you stub db queries in db)

  • 1 + 2 => @articles should contain one article, that's your spec expectation

Arturo Herrero
  • 12,772
  • 11
  • 42
  • 73
apneadiving
  • 114,565
  • 26
  • 219
  • 213
1

In a controller spec, assigns will take a symbol (e.g. assigns(:variable)) and returns the controller's corresponding instance variable (e.g. @variable in the controller).

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.

assigns has been moved into a gem: https://github.com/rails/rails-controller-testing.

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

Matthias
  • 648
  • 6
  • 18