【问题标题】:Stubbed method returns nil inside a before_create callback存根方法在 before_create 回调中返回 nil
【发布时间】:2011-11-18 12:10:39
【问题描述】:

我在我的模型中测试 before_create 回调处于死胡同。

我的规格

# The spec
let(:stamp){ mock_model(CompanyStamp) }
let(:signature){ mock_model(CompanyHandwrittenSignature) }
let(:account) { mock_model(Account, :company_handwritten_signature => signature, :company_stamp => stamp) }
it "should have signature if the account has signature" do
  subject.stub :account => account
  subject.stub :save => true
  subject.company_handwritten_signature.should == signature
end

这是我的模型代码

# the model's code
before_create do |element|
  puts "element.account ===> #{element.account.inspect}"  # element has no account! wtf!?
  element.company_handwritten_signature ||= element.account.company_handwritten_signature
  element.company_stamp ||= element.account.company_stamp
  true
end

正在调用 before_filter 方法,但在该回调中,account 方法的存根似乎不起作用。 我已经测试过了

subject.account = account
结果相同。这是怎么回事?

顺便说一句,我使用的是 rails 2.3 和 rspec-rails 1.3.4

【问题讨论】:

    标签: ruby-on-rails ruby callback rspec stubbing


    【解决方案1】:

    你存根方法的方式看起来不对。我一直在使用类似的东西:

    subject.stub(:method).and_return(value)
    

    你试过这种格式吗?另外,你为什么要存根保存?看起来这可能会影响一些预期的 ActiveRecord 行为。

    let(:stamp){ mock_model(CompanyStamp) }
    let(:signature){ mock_model(CompanyHandwrittenSignature) }
    let(:account) { mock_model(Account, :company_handwritten_signature => signature, :company_stamp => stamp) }
    it "should have signature if the account has signature" do
      subject.stub(:account).and_return(account)
      subject.stub(:save).and_return(true)
      subject.company_handwritten_signature.should == signature
    end
    

    【讨论】:

    • subject.stub(:method).and_return(value) 和 subject.stub :account => account 是一样的。它只是语法糖,但我使用了具有相同结果的长语法。如果真的调用 save 我有帐户,那么会有一些意外的 active_record 行为。当我保存时,我得到一个 sql 错误:ActiveRecord::StatementInvalid in 'TransportDocument INSTANCE METHODS STAMP AND SIGNATURE should have signature if the account has signature' Mysql::Error: Cannot add or update a child row: a foreign key constraint failed
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多