Sequences
これはよく使う
factory :post do
author
sequence(:title) {|n| "test#{n}"} ←これ
end
test1,test2,test3と連番でvalueをセットできるよ
ignore
これは僕は知らなかった
factories/users.rb
FactoryGirl.define do
factory :user, aliases: [:author] do
name 'murajun1978'
password 'murajun1978'
password_confirmation { |u| u.password }
factory :user_posts do
ignore do ←これ
count 1
end
after(:create) do |user, value|
FactoryGirl.create_list(:post, value.count, author: user)
end
end
end
factory :post do
author
sequence(:title) {|n| "text#{n}"}
end
end
models/user.rb
require 'spec_helper'
describe User do
context "example1" do
subject {FactoryGirl.create(:user)}
its(:name){should eq 'murajun1978'}
end
context "example2" do
subject {FactoryGirl.create(:post)}
its("author.name"){should eq "murajun1978"}
end
context "example3" do ←これ
before {FactoryGirl.create(:user_posts, count: 5)}
it {Post.should have(5).posts}
it {User.should have(1).user}
end
end
countを引数で指定するとそのレコード数だけ作成してくれる
countを指定しなければデフォルト値がセットされるよ
上の例だと1回だね
ちなみに…
have(5).postsのpostsは任意なのでitemsとかなんでもおkヘ(^o^)ノ
0 件のコメント:
コメントを投稿