【问题标题】:Testing Rails ActiveRecord before_create method with Rspec使用 Rspec 测试 Rails ActiveRecord before_create 方法
【发布时间】:2012-09-18 16:12:47
【问题描述】:

我发现 that stackoverflow old post 建议 model_entity.send(:before_create) 但现在它不起作用。那么,我该如何测试应该执行 before create, update, destroy 的方法。还有另一个 post 但我不知道,在我的情况下我应该做什么。

class User < ActiveRecord::Base

  before_create do |user|
    user.secure_token = UUID.new.generate
  end
end

关键是我可以用这段代码创建一个方法,然后调用它。还有其他方法吗?

一般来说,如果我想测试只存在于我的模型中的 after_create 方法,我应该创建模型对象并检查它。但是,我想,这是不必要的行动。我可以在不创建任何实例的情况下检查此方法。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 unit-testing activerecord rspec


    【解决方案1】:

    有一个干巴巴的方法:

    expect{ user.save }.to change{ user.secure_token }
    

    【讨论】:

      【解决方案2】:

      刚刚发现了一些棘手的问题。如果您需要验证实际结果,请单独验证,因为如果您使用 .should_receive(:secure_token=),当前 rspec 不会传递函数 :secure_token= 的返回值。示例:

      型号如上:

      describe "verifies that secure_token= is called" do
        @user = User.new
        @user.should_receive(:secure_token=)
        @user.save
      end
      
      describe "verifies the result is set" do
        @user = User.new
        @user.save
        expect(@user.secure_token).not_to be_empty
      end
      

      但是如果你把expect not 和should_receive 放在同一个测试中,那么测试就会失败。

      【讨论】:

        【解决方案3】:

        如果你使用 rspec,我猜你可以这样做:

        @user = User.new
        @user.should_receive(:secure_token)
        @user.save
        

        【讨论】:

        • 那么,如果它不应该接收它会抛出一些东西?我怎样才能将其形成为测试。 before(:each) do @user = User.new end it "should have a secure_token" do @user.should_receive(:secure_token) @user.save end
        • 正如错误所说,您的测试期望“在保存对象期间调用 'secure_token' 方法一次”,但不知何故,您的代码调用了此方法两次。看起来,还有一些其他的回调方法(在用户对象中)在这个对象上设置了secure_token。
        • 是的,有一个验证。如果它调用,那么它确实调用了两次。
        • 所以你可以做两件事:@user.should_receive(:secure_token).twice,或者@user.save(:validate => false)(保存而不验证)
        • 不应该是@user.should_receive(:secure_token=) 注意=...?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-03
        • 1970-01-01
        • 2013-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多