如何在Rails Minitest中伪造方法

时间:2019-07-12 11:32:10

标签: ruby-on-rails minitest

我试图伪造对方法调用的响应,但没有成功。

在我的测试中,呈现html的页面将显示来自其中的页面数。调用<%= @pagy.pages %>(我使用的是Pagy gem),但是在我的测试中,我不需要对页面进行计数,只需要检查页面是否已打开即可。

因此,@ pagy从未在测试中初始化。

我需要Minitest来“伪造” @pagy.pages的答案,以便始终响应数字1

该怎么做?

谢谢!


在@Ahmed回答之后,这是新代码,但仍然无法正常工作:

    mock = MiniTest::Mock.new
    mock.expect :pages, 1

    Pagy.stub :new, mock do
      create :lando, :brazilo
      get '/ameriko/brazilo'
      assert_response :success
    end

该视图仍然找不到@pagy.pages方法。

1 个答案:

答案 0 :(得分:1)

您可以在setup块中使用Minitest Mocks(如果将此代码放入测试用例块本身也可以使用):

mock = Minitest::Mock.new
mock.expect :pages, 1

Pagy.stub :new, mock do
  # Put the code that relies on `@pagy.pages` is `1`
end

回溯:

Minitest::UnexpectedError: ActionView::Template::Error: undefined method `pages' for nil:NilClass
    app/views/events/_events_as_cards.haml:11:in `_app_views_events__events_as_cards_haml__846217806806687455_70361502341700'
    app/helpers/events_helper.rb:27:in `display_events_by_style'
    app/views/events/by_country.haml:20:in `_app_views_events_by_country_haml__4566190630208235120_70361501243420'
    test/controllers/events_controller_test.rb:41:in `block (2 levels) in <class:EventsControllerTest>'
    test/controllers/events_controller_test.rb:39:in `block in <class:EventsControllerTest>'
app/views/events/_events_as_cards.haml:11:in `_app_views_events__events_as_cards_haml__846217806806687455_70361502341700'
app/helpers/events_helper.rb:27:in `display_events_by_style'
app/views/events/by_country.haml:20:in `_app_views_events_by_country_haml__4566190630208235120_70361501243420'
test/controllers/events_controller_test.rb:41:in `block (2 levels) in <class:EventsControllerTest>'
test/controllers/events_controller_test.rb:39:in `block in <class:EventsControllerTest>'
Finished in 1.53247s
1 tests, 0 assertions, 0 failures, 1 errors, 0 skips
I, [2019-07-15T10:00:50.384204 #47531]  INFO -- : Running locally, skipping Codacy coverage

Process finished with exit code 1