首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >simplecov类测试示例

simplecov类测试示例
EN

Stack Overflow用户
提问于 2016-09-27 11:35:26
回答 1查看 77关注 0票数 0

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

我如何在simplecov中测试下面的类?

如何在rspec中测试save_user方法?

代码语言:javascript
复制
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 
EN

回答 1

Stack Overflow用户

发布于 2016-09-27 12:58:21

有几个问题正在发生:

代码语言:javascript
复制
has_one :user
belongs_to :user

同时使用'has_one‘和'belongs_to’关系来引用同一个模型是很不寻常的。通常情况下,您只需要其中之一。(例如,如果日志有一个user_id字段,那么您只需要belongs_to,而不需要has_one)

代码语言:javascript
复制
self.user_id = :current_user

如果您试图调用一个方法而不是存储一个符号,那么您可能需要current_user而不是:current_user

为了测试after_save的实际运行情况,我推荐这样的代码:

代码语言:javascript
复制
log = Log.new
expect(log).to receive(:after_save).and_call_original
log.save
expect(log.user).to eq(current_user)

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39715559

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档