【问题标题】:Rspec how to check whether table hasn't beed modifiedRspec如何检查表是否没有被修改
【发布时间】:2013-09-05 16:39:02
【问题描述】:

我正在为我的应用程序编写测试(rspec-rails)。我想检查正在运行的脚本是否没有更改表中的任何对象。 我尝试使用 Table.hash 或仅添加每个对象哈希,但是当我对对象进行一些更改时,这些值不会改变。所以执行这段代码后(Someobject只是一个例子-普通表):

hash1a = Someobject.hash
o = Someobject.first 
hash2a = o.hash
o.field = o.field + 1
o.save!
hash1b = Someobject.hash
hash2b = o.hash

hash1a == hash1bhash2a == hash2b。所以很明显我不能使用这些方法中的任何一个来检查是否有任何对象发生了变化。

目前我正在使用此代码:

def run_script #run script and btw check whether it throws exception
    lambda { eval File.read(File.join(Rails.root, 'lib', 'tasks', 'some_script.rb')) }.should_not raise_error()
  end

  def objects_hash #calculates hash of each order json version and than concatenates all strings and return it
    hash = ''
    Someobject.each do |object|
      hash+= Digest::SHA1.base64digest object.as_json.to_s
    end
    hash
  end


  ....

expect {run_script}.to_not change{objects_hash} #expect run_script to not change any object

基本上它将每个对象转换为 json,然后转换为字符串,然后计算该字符串的哈希值。所有字符串(哈希)都连接起来 并返回此值。所以这条线expect {run_script}.to_not change{objects_hash} #expect run_script to not change any object 计算所有对象的哈希,运行脚本,计算新哈希并将新哈希与旧哈希进行比较。

它工作正常,但我认为有更好的方法来实现这一点。问题是——如何?我正在使用 rails 3.2.13 和 mongoid。

【问题讨论】:

  • 似乎是查看集合中是否有任何文档发生更改的合理解决方案,除非您想检查日志文件等。
  • 我不需要检查日志文件等(只是一个表的所有对象),但我只是在所描述的情况下寻找更好的解决方案。
  • 我是说您也许可以使用日志文件来查找修改。但是,正如我所说,我看不出有任何理由不按照你的建议去做。它不会非常快,但对于您拥有的用例,这似乎不是问题。
  • 使用这个命令:db.runCommand({dbhash:1})
  • @AsyaKamsky - 您的解决方案(稍作修改)有效,非常感谢!最后我使用了这个代码expect {run_script}.to_not change{Mongoid::Sessions.default.command(dbHash:1)['collections']['tablename']},它工作正常。请发表您的评论作为答案,以便我接受。

标签: ruby-on-rails ruby mongodb hash rspec


【解决方案1】:

MongoDB 有一个数据库命令 dbhash - 分片在内部使用它来检查配置数据库集合是否已更改。

使用和输出示例:

> db.runCommand({dbhash:1})
{
    "numCollections" : 3,
    "host" : "asyasmacbook.local",
    "collections" : {
        "usertable" : "57fd76283e32631be17d03cd684ab7db"
    },
    "md5" : "b5cfcfca8dd0e4731676139aff4cf4e7",
    "timeMillis" : 274,
    "ok" : 1
}

将集合的哈希值与其之前的值进行比较,您可以确定其中是否有任何更改。

【讨论】:

  • 更准确地说 - 我使用了这个代码:expect {run_script}.to_not change{Mongoid::Sessions.default.command(dbHash:1)['collections']['tablename']}。当然,这个解决方案只适用于 Mongoid,但对我来说看起来比我提出的解决方案更好。
猜你喜欢
  • 2013-12-16
  • 1970-01-01
  • 2014-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 2016-05-05
相关资源
最近更新 更多