我们使用capybara集成测试来测试我们的前端管道(javascript)是否正确连接。
有时我们需要验证测试的全部内容是:
上面的第1项很容易。但是,对于第2项,我似乎无法找到一种简单的说法:
断言在浏览器中从js调用了url。
it "should call coorect url with correct query string" do
visit widgets_path
# THIS IS WHAT I NEED TO KNOW
expect(something).to receive(:some_method).with(url: "my/test/url", params: {per_page: 2})
# In other words, I don't want the controller action to run. I don't care about the result since the controller is being tested elsewhere.
# I just need to know that the correct URL was called with the correct params.
within 'ul.pagination' do
click_on '2'
end
end
我试过模拟控制器动作,但没有办法检查参数。还是有吗?如果不检查参数,我怎么知道是否发送了正确的东西?我所知道的只是正确的路线,这还不够。
如果我可以检查参数,那么这将被解决......但是否则呢?
答案 0 :(得分:1)
如果您正在寻找Rails解决方案,请点击此处!使用Rails 5.1.3进行测试。
1)创建请求参数匹配器spec/support/matchers/request_with_params.rb
RSpec::Matchers.define :request_with_params do |params|
match { |request| request.params.symbolize_keys.slice(*params.keys) == params }
end
2)为验收测试创建一个帮助方法(你可以使用一些逻辑来传递符号而不是类UsersController - >:用户,如果需要的话)
def expect_request(controller, action, params = {})
expect_any_instance_of(ActionDispatch::Routing::RouteSet::Dispatcher)
.to receive(:dispatch)
.with(controller, action.to_s, request_with_params(params), anything)
end
end
3)使用它!
expect_request(UsersController, :index)
或使用params
expect_request(UsersController, :show, { id: 1 })
OR
4)使用https://github.com/oesmith/puffing-billy还有另一种方法检查此gem以拦截浏览器发送的请求。但是,如果您只需要模拟对后端应用程序的某些请求,那就太过分了。
答案 1 :(得分:0)
Capybara集成测试故意不支持。它们是端到端的黑盒测试,通常不应该被模拟,并且实际上仅支持在浏览器中检查用户可见的内容。在您的示例中,这意味着期望由JS调用特定URL引起的任何可见更改。像
这样的东西expect(page).to have_css('div.widget', count: 2)