【问题标题】:RSpec. How to check if the object method is called?规范。如何检查对象方法是否被调用?
【发布时间】:2012-04-09 04:58:52
【问题描述】:

我正在为控制器编写规范:

it 'should call the method that performs the movies search' do
  movie = Movie.new
  movie.should_receive(:search_similar)
  get :find_similar, {:id => '1'}
end

我的控制器看起来像:

def find_similar
 @movies = Movie.find(params[:id]).search_similar
end

运行 rspec 后,我得到以下信息:

Failures:
1) MoviesController searching by director name should call the method that performs the movies search
 Failure/Error: movie.should_receive(:search_similar)
   (#<Movie:0xaa2a454>).search_similar(any args)
       expected: 1 time
       received: 0 times
 # ./spec/controllers/movies_controller_spec.rb:33:in `block (3 levels) in <top (required)>'

我似乎理解并接受,因为在我的控制器代码中我调用了类(电影)方法,但我没有看到任何将“find_similar”与规范中创建的对象连接起来的方法。

所以问题是 -> 检查方法是否在规范中创建的对象上调用的方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:
    it 'should call the method that performs the movies search' do
      movie = Movie.new
      movie.should_receive(:search_similar)
      Movie.should_receive(:find).and_return(movie)
      get :find_similar, {:id => '1'}
    end
    

    值得一提的是,我完全反对这些 stub-all-things 测试,它们只是使代码更改更加困难,实际上只测试代码结构。

    【讨论】:

    • 同意过度存根,看到太多测试检查方法存根是否有效,而不是检查应用程序是否有效。
    • 不错的一个。这是津津乐道的文档:relishapp.com/rspec/rspec-mocks/v/2-5/docs/message-expectations我需要这个位obj.should_receive(:message).with('more_than', 'one_argument')
    • ”标签的有趣用法
    【解决方案2】:

    起初,您的电影尚未持久化。

    其次,不是事实,它的 id 为 1

    所以试试这个

    it 'should call the method that performs the movies search' do
      movie = Movie.create
      movie.should_receive(:search_similar)
      get :find_similar, {:id => movie.id}
    end
    

    【讨论】:

    • 感谢“id”,您说的完全正确。然而,主要问题仍然存在,更改代码后消息相同 - >失败/错误:movie.should_receive(:search_similar) (#<0xae08b48>
    猜你喜欢
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多