読者です 読者をやめる 読者になる 読者になる

tkymtk's blog

Ruby on Rails及びその周辺について調べたこと。Do whatever you want to do at your own pace.

Ruby on Rails Tutorial Chapter10 FactoryGirlを使って/使わないで書くRSpec

前準備

# spec/factory.rb
FactoryGirl.define do
  factory :user do
    sequence(:name) { |n| "Person#{n}"}
    sequence(:email) { |n| "Person_#{n}@example.com"}
    password "foobar"
    password_confirmation "foobar"

    factory :admin do
      admin true
    end
  end

  factory :micropost do
    content "Lorem ipsum"
    user
  end
end

RSpec

describe User do
  let(:user) { User.new(name: "Example User", email:"foo@example.com", password: "foobar", password_confirmation: "foobar") }

  subject { user }

  # ここにかく

end

FactoryGirlを使う

  describe "micropost associations" do
    before { subject.save }

    let!(:older_micropost) do
       FactoryGirl.create(:micropost, user: subject, created_at: 1.day.ago)
     end

    let!(:newer_micropost) do
       FactoryGirl.create(:micropost, user: subject, created_at: 1.hour.ago)
    endend

FactoryGirlを使わない

  describe "micropost associations" do
    before { subject.save }

    let!(:older_micropost) do
      user.microposts.create!(content: "Lorem ipsum", created_at: 1.day.ago)
     end

    let!(:newer_micropost) do
      user.microposts.create!(content: "Lorem ipsum", created_at: 1.hour.ago)
    endend

リンク

間違いがあれば、ご指摘下さると幸いです。