1

我正在使用 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
4

3 回答 3

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应该显示至少 2Articles

你可以用一个简单的断言来测试这个,比如expect(@article.size).to eq(2)

于 2013-04-24T13:45:24.847 回答
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
于 2013-04-24T14:14:25.423 回答
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
于 2013-04-24T15:53:29.593 回答