What does assigns mean in rspec

2020-07-02 07:02发布

问题:

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

回答1:

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