25

私が遭遇するほとんどすべてのスペックファイルは、次のようなものを書くことになります。

  before :each do
    @cimg = Factory.build :cimg_valid
    @cimg.stub(:validate_img).and_return true
    @cimg.stub(:validate_img_url).and_return true
    @cimg.stub(:save_images).and_return true
    @cimg.stub(:process_image).and_return true
    @cimg.stub(:img).and_return true
  end

つまり、Factory.buildから取得したモデルは完全に有効です。しかし、そのようなものをスタブしないと、ファイルシステムに保存され、テストしていないものを検証します...

つまり、次のようなことを行う方がクリーンだと思います。

  before :each do
    @cimg = Factory.build :cimg_for_testing_tags
  end

工場内でスタブすることさえ可能であるならば。

モデルをスタブする適切な方法は何ですか?

4

4 に答える 4

33

@fkreuschの答えは、新しいRSpecexpect()構文(3.0以降)を使用するまではうまく機能します

これを私のためにrails_helper.rb機能させる:

FactoryBot::SyntaxRunner.class_eval do
  include RSpec::Mocks::ExampleMethods
end

OPの例では、次のことができます。

FactoryBot.define do
  factory :cimg_for_testing_tags do

    ... # Factory attributes

    after(:build) do |cimg|
      allow(cimg).to receive(:validate_img) { true }
    end
  end
end

クレジット:github.com/printercu、参照:https ://github.com/thoughtbot/factory_bot/issues/703#issuecomment-83960003

于 2015-06-30T04:16:57.427 に答える
22

factory_girlの最近のバージョンでは、after_buildコールバックがあるので、次のようにファクトリを定義できると思います。

FactoryGirl.define do
  factory :cimg_for_testing_tags do

    ... # Factory attributes

    after_build do |cimg|
      cimg.stub(:validate_img).and_return true
    end
  end
end

アップデート

factory_girl 3.3.0以降、構文は次のように変更されました。

FactoryGirl.define do
  factory :cimg_for_testing_tags do

    ... # Factory attributes

    after(:build) do |cimg|
      cimg.stub(:validate_img).and_return true
    end
  end
end
于 2012-01-31T00:51:25.930 に答える
5

ファクトリは「実世界」のオブジェクトを生成する必要があるため、ファクトリの動作(つまりスタブ)を変更することは悪い習慣(そしてエラーが発生しやすい)です。

できるよ

let(:user) instance_double(User, FactoryGirl.attributes_for(:user))

before do
  allow(user).to receive(:something).and_return('something')
end

句が大きくなりすぎる場合は、before句を別のメソッドに抽出するか、スタブするメソッドをオーバーライドするモック子クラスを作成することをお勧めします。

于 2017-09-05T15:52:41.190 に答える
3

FactoryGirl#build_stubbedの使用を検討することもできます。

于 2014-06-06T16:28:37.773 に答える