0

いくつかの RSpec/Rails テストをリファクタリングして、データベースに保持されるオブジェクトをできるだけ少なくしようとしていますが、次のようなテストを書き直す方法を見つけようとして問題が発生しています。

describe User do
  context "record creation" do
    before(:each) { @user = User.new(user_atts) }

    it "should generate a confirmation_token" do
      # Generated as the result of a callback
      @user.save!
      expect(@user.confirmation_token).to be_present
    end

    it "should set the confirmed_at attribute to nil" do
      # Cleared as the result of a callback
      @user.save!
      expect(@user.confirmed_at).to be_nil
    end

    it "should call the send_confirmation_instructions method" do
      @user.should_receive(:send_confirmation_instructions) {}
      @user.save!
    end
  end

  def user_atts
    # return attributes hash
  end
end

これは非常に単純な例ですが、私の仕様には似たようなインスタンスがたくさんあり、ほとんどの場合、それらはすべてレコードをデータベースに永続化します。私は RSpecletsubjectヘルパーを利用したいと思っていますが、それらがここで役立つかどうかは完全にはわかりません。

私はFactoryGirlを頻繁に使用しており、そのbuild_stubbed戦略によってスペックが少し高速化されるのではないかと考えていましたが、実際のレコード作成を制限するのに役立つ例はあまり見つかりませんでした (または、使用方法がわからない可能性があります)。

テストでレコードの作成が必要になる場合もあると思いますが、上記の例はそのようなものではないようです。これをリファクタリングしようとする必要がありますか、それともこれらのテストを作成する方が良いですか? どんな助けでも大歓迎です。

4

1 に答える 1

2

私のテストはおそらく次のようになります。

describe User do
  let(:user) { FactoryGirl.build_stubbed(:user) } 

  context "record creation" do
    it "should generate a confirmation_token" do
      user.save!
      expect(user.confirmation_token).to be_present
    end

    it "should set the confirmed_at attribute to nil" do
      user.save!
      expect(user.confirmed_at).to be_nil
    end

    it "should call the send_confirmation_instructions method" do
      expect(user).to receive(:send_confirmation_instructions).once
      user.save!
    end
  end
end

Factory Girl を使用してユーザー モデルを作成しています。また、@RahulGarg で述べられているように、各テストの後に DatabaseCleaner でデータベースをクリアする必要があります。

あなたがしなければならないのは、あなたのspec_helperでこのようなものを設定することだけです

  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

これは、各テストの後にデータベースがクリアされることを意味します。

于 2013-01-21T19:11:11.423 に答える