【发布时间】:2018-05-23 23:42:51
【问题描述】:
在某个页面的 Capybara 功能规范中,我有一个下载链接:
download_link = find_link(expected_link_text)
我想检查生成的链接是否是下载文件的正确链接,即它将使用正确的模型对象在我的 FileController 上调用 download()。
RSpec-Rails 似乎有很多方法可以得到我想要的。例如,在controller spec 中,我可以在控制器上使用普通的 RSpec 断言:
expect(controller).to receive(:download).with(expected_id)
# download_link = find_link(expected_link_text) # can't do this in a controller spec
# visit(download_link) # can't do this in a controller spec
在路由规范中,我可以使用 route_to():
# download_link = find_link(expected_link_text) # can't do this in a routing spec
expect(get: download_link[href]).to route_to(controller: 'file', action: 'download', id: expected_id)
但在功能规范中,controller 和 route_to() 均不可用。
通过以下恶作剧和在调试器中的大量探索,我能够将route_to() 包含在我的测试中:
describe 'the page' do
it 'should let the user download a file' do
self.class.send(:include, RSpec::Rails::Matchers::RoutingMatchers) # hack to get routing matchers into feature test
self.class.send(:include, ActionDispatch::Assertions::RoutingAssertions) # RoutingMatchers uses this internally
self.class.send(:define_method, :message) { |msg, _| msg } # RoutingAssertions expects message() to be included from somewhere
@routes = Rails.application.routes # RoutingAssertions needs @routes
download_link = find_link(expected_link_text)
expect(get: download_link[href]).to route_to(controller: 'file', action: 'download', id: expected_id) # works!
end
end
这确实有效,但它是香蕉。是否有任何开箱即用的方法可以将 Capybara 混合到其他类型的规格中,或者将其他类型的规格混合到功能规格中?或者只是一种更清洁的 Rails-y(可能是非 RSpec)方式来获取路线?
注意:路由没有命名,所以我不能使用 URL 助手(我不认为);由于历史原因,URL 路径本身是不连贯的噪音,所以我不只是想以字符串形式断言 href。
【问题讨论】:
标签: capybara rspec-rails