【问题标题】:simplecov class test examplesimplecov 类测试示例
【发布时间】:2016-09-27 03:35:26
【问题描述】:

我需要为这个类实现 100% 的代码覆盖率。

如何在 simplecov 中测试以下类?

如何在 rspec 中测试 save_user 方法?

class Log < ActiveRecord::Base
  has_and_belongs_to_many :tags
  has_one :asset
  has_one :user
  belongs_to :user

  after_create :save_user

  def save_user
    self.user_id = :current_user
    self.save()
  end
end
describe Log do
    context "When saving a user is should save to the database."

    it "should call insert fields with appropriate arguments" do
    expect(subject).to receive(:asset).with("TestData")
    expect(subject).to receive(:user).with("DummyName")
    expect(subject).to save_user 
    subject.foo
end
end 

【问题讨论】:

  • 请为您的问题添加更多上下文。

标签: ruby-on-rails rspec simplecov


【解决方案1】:

有几个问题正在发生:

has_one :user
belongs_to :user

同时具有“has_one”和“belongs_to”关系来指代同一个模型是不寻常的。通常你只需要一个或另一个。 (例如,如果 Log 有一个 user_id 字段,那么您只需要 belongs_to 而不需要 has_one

self.user_id = :current_user

如果您尝试调用方法而不是存储符号,您可能需要current_user 而不是:current_user

要测试after_save 是否实际运行,我建议使用类似的方法:

log = Log.new
expect(log).to receive(:after_save).and_call_original
log.save
expect(log.user).to eq(current_user)

在新实例上调用 save 将触发 after_create 运行,然后您可以验证结果并检查它是否正确运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 2019-01-19
    • 2017-02-06
    • 2015-10-14
    相关资源
    最近更新 更多