【问题标题】:Pass mocked API object to rails controller during test在测试期间将模拟的 API 对象传递给 rails 控制器
【发布时间】:2014-10-27 18:59:24
【问题描述】:

我的问题是关于测试 (MiniTest) 一个查询 API 的 Rails 4.0 控制器。例如,我有这个控制器:

class InsolentController

    def show 

        @result = SomeApi.get value1, value2

    end

end

现在我想在不调用我的 API 的情况下对其进行测试,所以如果我使用 ASP.NET MVC,我可以这样做:

public Class InsolentController
{
    private SomeAPI someApi;

    public InsolentController(SomeAPI api = null)
    {

        this.someApi = api ?? new SomeAPI();
    }

    public ActionResult Show()
    {
        var result = this.someApi.Get(value1, value2);

        // return, etc...
    }
}

我这样做是为了模拟 SomeAPI。那么,当我想将 MiniTest 与 rails 一起使用时,我该如何处理,例如:

require 'test_helper'

class InsolentControllerTest < ActionController::TestCase

    test "should get show" do

        get :show, { value1: 10, value2: 34 }

        assert_response :success
    end

end

【问题讨论】:

  • 我正在研究一个类似的问题,你有没有想过这个问题?
  • 嗨,汤姆,不,我没有。无论如何,我只是在玩 Rails 框架,所以这没什么大不了的,但也许它会在此过程中对某人有所帮助。真好,您根据自己的回答想通了。

标签: api ruby-on-rails-4 controller tdd minitest


【解决方案1】:

我最终使用 rspec-mocks 并使用 minitest 进行设置。

您应该可以轻松地执行以下操作:

require 'test_helper'

class InsolentControllerTest < ActionController::TestCase

  test "should get show" do
    value1 = 10
    value2 = 34
    expect(SomeApi).to receive(:get).with(value1, value2)

    get :show, { value1: value1, value2: value2 }
    assert_response :success
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多