【问题标题】:Test controller with rspec - need to stub before_save使用 rspec 测试控制器 - 需要存根 before_save
【发布时间】:2012-10-03 14:35:10
【问题描述】:

我有User.rb 模型:

before_save { self.email.downcase! }

我需要在users_controller_spec.rb 中存根这个方法:

User.any_instance.stubs(:before_save_callback_method).returns(true) #doesn't work
User.any_instance.stubs(:valid?).returns(true) #works

我该怎么做?

【问题讨论】:

    标签: ruby-on-rails-3 rspec mocha.js stub


    【解决方案1】:

    您实际上不需要存根 before_save 回调,而是可以存根回调调用的方法。您可以将行为移至方法并改为存根。

    before_save :downcase_email
    
    def downcase_email
      self.email.downcase!
    end
    

    然后在您的规格中:

    user.stub(:downcase_email).and_return(true)
    

    【讨论】:

      【解决方案2】:

      如果你使用mock,可以这样完成

      describe User
        it "should accept email_downcase before save" do
          user = mock(User)
          user.should_receive(:email_down).and_return(email.downcase) # => use return in case you want to
        end
      end
      

      谢谢

      【讨论】:

      • 谢谢你,@Paritosh Singh。不幸的是它不能解决问题。因为问题是“创建”后的错误:未定义的方法“小写!”对于零:NilClass。 @beef jerky 给出了正确答案。
      【解决方案3】:

      你真的需要 before_save 方法吗?如果您覆盖 email= 可能会更好,因此电子邮件在分配后立即被小写,而您甚至在保存记录之前就已将其小写

      User < ActiveRecord
        def email=(value)
          write_attribute(:email, value.downcase)
        end
      end
      

      我不知道这对您的测试是否有帮助,但有时这比 before_save 回调更好

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-04
        • 1970-01-01
        • 1970-01-01
        • 2011-07-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多