3

モデルにコードがあります。

class Foo < ActiveRecord::Base
 after_create :create_node_for_foo

   def create_node_for_user
     FooBar.create(id: self.id)
   end
end

Fooモデルのrspecにコードがあります

describe Foo do

  let (:foo) {FactoryGirl.create(:foo)}

  subject { foo }
  it { should respond_to(:email) }
  it { should respond_to(:fullname) }

 it "have mass assignable attributes" do
  foo.should allow_mass_assignment_of :email
  foo.should allow_mass_assignment_of :fullname
 end

 it "create node in graph database" do
   foo1 = FactoryGirl.create(:foo)
   FooBar.should_receive(:create).with(id: foo1.id)
 end
end

しかし、私のテストはメッセージで失敗しています

Failures:

   1) Foo create node in graph database on
      Failure/Error: FooBar.should_receive(:create).with(id: foo1.id)
      (<FooBar (class)>).create({:id=>18})
       expected: 1 time
       received: 0 times

何が悪いのでしょうか?

4

3 に答える 3

3

さて、問題を回避しました

これを変更しました

 it "create node in graph database" do
  foo1 = FactoryGirl.create(:foo)
  FooBar.should_receive(:create).with(id: foo1.id)
end

 it "create node in graph database" do
  foo1 = FactoryGirl.build(:foo)
  FooBar.should_receive(:create).with(id: foo1.id)
  foo1.save
end
于 2013-01-01T13:14:52.553 に答える
1

パーティーに少し遅れましたが、実際には上記は機能しません。それを行うためのカスタム マッチャーを作成できます。

class EventualValueMatcher
  def initialize(&block)
    @block = block
  end

  def ==(value)
    @block.call == value
  end
end

def eventual_value(&block)
  EventualValueMatcher.new(&block)
end

次に、仕様で次のことを行います。

it "create node in graph database" do
  foo1 = FactoryGirl.build(:foo)
  FooBar.should_receive(:create).with(eventual_value { { id: foo1.id } })
  foo1.save
end

これは、実際にブロックが設定されるまで、モックはブロックを評価しないことを意味します。

于 2013-12-18T03:17:13.363 に答える