简体   繁体   English

Rspec应该在Sinatra和Rails中收到期望的不同行为

[英]Rspec should_receive expectation different behaviour in Sinatra and Rails

So, let's consider we have two models, A1 and A2, and A1 has_many A2, while A2 belongs_to A1. 因此,让我们考虑我们有两个模型,A1和A2,A1 has_many A2,而A2属于A1。 According to the ActiveRecord Spec, if you instantiate from A1, and try to create a resource in the a2 collection, it triggers an exception, saying the parent needs to be saved in order for it to be saved: 根据ActiveRecord规范,如果您从A1实例化,并尝试在a2集合中创建资源,则它将触发一个异常,表示需要保存父对象才能保存它:

a1 = A1.new
a1.a2s.create #=> BOOM! Exception

Til here, all clear. 直到这里,一切都清楚了。 But now I have an Rspec test for the case, in which I have an unsaved A1 instance, and then I do: 但是现在我有一个Rspec测试,其中有一个未保存的A1实例,然后执行此操作:

a1.a2s.should_receive(:create)
a1.a2s.create

And this is where the milk turns sour. 这就是牛奶变酸的地方。 I have these AR Models replicated in a Sinatra app and a Rails App. 我将这些AR模型复制到Sinatra应用程序和Rails应用程序中。 When I run it in Rails, the spec runs, since the expectation was matched, even though it raised an Exception. 当我在Rails中运行它时,规范会运行,因为期望符合要求,即使它引发了Exception。 In Sinatra, though, it just raises the Exception, not accepting the test. 但是,在Sinatra中,它仅引发Exception,而不接受测试。

Can someone tell me why? 有人可以告诉我为什么吗? I thought it was an Rspec issue, but they don't acknowledge it as such. 我以为这是Rspec的问题,但他们不这样认为。

How are you storing your data in the Sinatra app? 您如何将数据存储在Sinatra应用程序中?

In ActiveRecord, a1.a2s gives you the same ActiveRecord::Relation instance both times, so the expectation is bound to the instance that calls create . 在ActiveRecord中, a1.a2s为您提供相同的ActiveRecord::Relation实例,因此期望值绑定到调用create的实例。

My guess is that in Sinatra a1.a2s is returning a new instance each time it's called, so the expectation is not bound to the caller of create . 我的猜测是,在Sinatra a1.a2s中,每次调用时都会返回一个新实例,因此期望值并不绑定到create的调用者。

You could test my theory by running 您可以通过运行来检验我的理论

a1.a2s.object_id
a1.a2s.object_id

and seeing if both ids are the same. 并查看两个ID是否相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM