Ruby-on-rails Rspec:如何检查是否调用了对另一个类的方法的调用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4106031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:33:07  来源:igfitidea点击:

Rspec: how can I check if a call to a method of another class is called?

ruby-on-railsrspec2

提问by rtacconi

I can I check if FeedItem::populate_from_friend_to_user is called inside the user class?

我可以检查 FeedItem::populate_from_friend_to_user 是否在用户类中被调用?

    it "should auto populate feed after user.add_friend" do
      @user.add_friend(@friend1)
      @user.should_receive('FeedItem::populate_from_friend_to_user').with(@friend1, @user)
    end

With the above code I get:

通过上面的代码,我得到:

undefined method `populate_from_friend_to_user' for :FeedItem:Symbol

回答by shingara

You should not know wherethe method is called, just ifthe method is called.. You just know if the method is call:

你不应该知道方法在哪里调用,只知道方法是否被调用..你只知道方法是否被调用:

Before RSpec 3

在 RSpec 3 之前

 it "should auto populate feed after user.add_friend" do
    FeedItem.should_receive(:populate_from_friend_to_user).with(@friend1, @user)
    @user.add_friend(@friend1)
 end

In RSpec 3the syntax is

在 RSpec 3 中,语法是

expect(Object).to receive(:method).with(params)

回答by Adam Piotrowski

Remember that is works only in rspec2 . For rspec3 u call

请记住,这仅适用于 rspec2 。对于 rspec3 你打电话

expect(@user).to receive(:your_method)

expect(@user).to receive(:your_method)

https://www.relishapp.com/rspec/rspec-mocks/v/3-0/docs/message-expectations

https://www.relishapp.com/rspec/rspec-mocks/v/3-0/docs/message-expectations