2

私はファクトリーガールを使ったことがなく、今週からテストを始めたので、これらすべての新しいものは私を夢中にさせます. factory girl を使ってレコードを作成する簡単な方法を誰か説明してくれませんか?

ユースケースはこちら。キュウリを使用してユーザーを作成し、アカウント、ユーザー カテゴリなどの他のレコードも作成するテストを既に作成しました。今、私は 2 番目のテスト ケースを書いています。そこでは、テスト データが存在しないはずです (最初のテストから作成されたデータを使用できますが、他のテスト ケースからの依存は必要ありません)。したがって、factory girl を使用して、自分用のユーザーと関連するユーザー レコードを作成したいと考えています。ここでは、工場の女の子を使用せずに機能する私のテストを示します。

@no-database-cleaner
Feature: Managing users parent child relationships
  In order to use portal
  I want to create parent child relationships

  Scenario:  Creating a child user 
    Given I am on the homepage

    When I attempt to sign in with following user account:
      | email address         | password |
      | abc@company1.com   | password |

    Then I should see "abc@company1.com" message on page
    When I follow "All Child Users"
    Then I should see "Add Sub Child"
    When I click "Add Sub Child"
    Then I should see "Child Sub User"
    And I fill in "Email" with "xyztest@gmail.com"
    And I select "Medium" from "user_filter"
    And I choose "abc_id_yes"
    When I press "Create Child User"
    Then I should see "Child User is successfully created."
    And appropriate records should get created for the child user for new abc_id

そして、ステップ定義には次のようなコードがあります

Then(/^appropriate records should get created for the child user for new abc_id$/) do
  parent_user = User.find_by_email("abc@company1.com")
  user = User.find_by_email("xyztest@gmail.com")
  account = Account.find_by_user_id(parent_user)
  user.default_filter_level.should be_true
  user.ar_id.should be_true
  user.parent_id.should == parent_user.id
  filter = Filter.find_by_user_id(user.id)
  filter.user_id.should == user.id
  filter.abc_id.should be_true
  filter.account_id.should == account.id
end

したがって、関連付けられたレコードも作成する factory girl を使用して同じ結果を得るにはどうすればよいでしょうか。ありがとう

4

1 に答える 1

5

他のテストがこれに依存するべきではないというのは本当です。Given an user with other models existsその他のシナリオでは、次の定義でステップを追加します。

Given(/^an user with other models exists$/) do
  parent = FactoryGirl.create(:user)
  user = FactoryGirl.create(:user, email: "xyztest@gmail.com" parent_id: parent)
  account = FactoryGirl.create(:account, user_id: user.id)
  FactoryGirl.create(:filter, user_id: user.id, account_id: account.id)
end

spec/factories/users.rb で (デフォルトの属性値を指定しますが、呼び出しでオーバーライドできますFactoryGirl.create()):

FactoryGirl.define do
  factory :user do
    email "abc@company1.com"
    default_filter_level true
    ar_id true
  end
end

spec/factories/filters.rb:

FactoryGirl.define do
  factory :filter do
    abc_id true
  end
end

spec/factories/accounts.rb で (これは単なる空のファクトリです。割り当てが必要になることが多い属性を指定できます):

FactoryGirl.define do
  factory :account do

  end
end

シナリオの最後のステップでは、適切なモデルが作成されているかどうかをテストしないでください。

And appropriate records should get created for the child user for new abc_id

代わりに、次のようなものを使用します。

When I follow "All Child Users"
Then the page should have newly created child user
于 2013-05-30T17:02:47.760 に答える