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 回答
0

如果它对某人有帮助,Dan Draper 解决方案的更新版本使用带有块的自定义匹配器,将是这样的:

# spec/support/eventual_value_matcher.rb

RSpec::Matchers.define :eventual_value do |expected|
  match do |actual|
    actual == expected.call
  end
end

和用法:

require "support/eventual_value_matcher" # or you can do a global require on the rails_helper.rb file

it "xxx" do
  foo1 = FactoryGirl.build(:foo)
  expect(FooBar).to receive(:create).with(eventual_value(proc { foo1.id }))
  foo.save!
end
于 2019-08-30T15:59:53.940 回答