2013-01-01 111 views
2

我在我的模型中有代碼。用rspec測試after_create

class Foo < ActiveRecord::Base 
after_create :create_node_for_foo 

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

,並有代碼美孚模型

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 

的RSpec的,但我的測試與消息

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 

沒有什麼可能是錯誤的?

回答

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 
+2

爲什麼這會改變什麼?我重構了一個完全像你的測試,但它仍然無法正常工作。任何想法爲什麼和/或RSpec在幕後做了什麼? –

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 

這意味着,模擬不評估塊,直到事後,它實際上已經集。