如何创建用户的文章

时间:2013-04-24 13:35:42

标签: ruby-on-rails bdd factory-bot rspec-rails

我正在使用RSpec,FactoryGirls测试控制器 这是我的工厂.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

我如何在这里创建用户的文章
这是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

3 个答案:

答案 0 :(得分:1)

您可以指定已有文章的用户工厂

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

  trait :with_articles do
    after :create do |user|
      FactoryGirl.create_list :article, 2, :user => user
    end
  end
end

然后在你的控制器测试中

FactoryGirl.create :user, :with_articles # => returns user with 2 articles

<强>更新

我认为您希望查看每个用户的所有文章..如果是这种情况使用

get :index, {:id => user.id}

以这种方式寻找用户并获取控制器中的所有文章

@user = User.find(params[:id]);
@articles = @user.articles

如果不是这样的话那么只是做

@articles =  Article.all

使用trait :with_articles后,应至少显示2 Articles

你可以用简单的断言来测试这个 期待(@ article.size).to eq(2)

答案 1 :(得分:1)

 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

     it "assign all atricles to @atricles" do
       get :index
       assigns(:atricles).your_awesome_test_check #  assigns(:articles) would give you access to instance variable
     end
  end
end

答案 2 :(得分:1)

旧版本,而不是特征,是:

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