Search code examples
ruby-on-railsbddfactory-botrspec-rails

How to create an article of the user


I am testing the controllers with RSpec, FactoryGirls.
It is my factories.rb

FactoryGirl.define do
  factory :user do |user|
    user.sequence(:name) { Faker::Internet.user_name }
    user.email Faker::Internet.email
    user.password "password"
    user.password_confirmation "password"
  end

  factory :article do
    user
    title Faker::Lorem.sentence(5)
    content Faker::Lorem.paragraph(20)
  end
end

How can i create an article of the user here
And this is articles_controller_spec

 describe ArticlesController do
      let(:user) do
        user = FactoryGirl.create(:user)
        user.confirm!
        user
      end

      describe "GET #index" do
        it "populates an array of articles of the user" do
          #how can i create an article of the user here
          sign_in user
          get :index
          assigns(:articles).should eq([article])
        end

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

Solution

  • The older version, instead of traits, is this:

    describe ArticlesController do
    
      ..
    
      describe "GET #index" do
        it "populates an array of articles of the user" do
    
          article = FactoryGirl.create(:article, :user => user)
    
          sign_in user
          get :index
          assigns(:articles).should eq([article])
        end
    
      ..
    
    end