我正在尝试为我的应用程序实现一些集成测试,以测试我已有的投票系统,但遇到了一些问题。首先,这是我试图通过的测试代码:
describe "vote_up_user" do
it "should update the user rating" do
click_link "user_up_arrow"
response.should have_selector("#user_rating", :content => "1")
end
end
这是被点击的链接:
<%= link_to image_tag("uparrowbig.png"), vote_up_user_path(@user), :method => :post,
:id => "user_up_arrow", :class => "arrow", :remote => true %>
对应的 Action :
respond_to :html, :js
def vote_up_user
@voted_on_user = User.find(params[:id])
current_user.vote_exclusively_for(@voted_on_user)
respond_with(@voted_on_user, :location => user_path(@voted_on_user))
end
如果有人感兴趣,相应的 votes/vote_up_user.js.erb:
$("user_rating").update('<%= @voted_on_user.plusminus.to_s %>')
$("user_up_arrow").update('<%= image_tag("uparrowbigselect.png") %>')
$("user_down_arrow").update('<%= image_tag("downarrowbig.png") %>')
我的问题是我在 click_link 行上不断失败,并出现以下错误:
Missing template votes/vote_up_user with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]}
我可以理解为什么会失败,因为我在指定路径中没有 html.erb 模板。我实际上有一个 js.erb 文件,因为这是一个 AJAX 调用,但它不包含在 :formats 数组中,因此找不到。那么我的问题是,确保集成测试单击链接时搜索 :js 格式的最佳方法是什么?这是我可以在测试中简单调整的东西还是我需要将其添加到链接帮助器中?
最佳答案
我怀疑它不起作用的原因是 RSpec 本身无法测试 Javascript。
当您将 remote => true
添加到链接时,它仅添加 data-remote="true"
作为链接的属性,这并不意味着任何没有 JavaScript 的东西。这就是您在错误 :formats=>[:html]
中看到的原因。它只会寻找 html View 。为了让 Rails 默认请求 .js.erb View ,您需要在请求的 URL 末尾添加 .js,或者实际使用 Javascript 来请求页面。
为了让 Javascript 在你的测试中实际运行,你需要使用像 Capybara 这样的东西。当您运行测试时,您实际上会看到浏览器启动,并且它将在浏览器中实际运行您的测试。
如果这就是您想要做的,我建议您观看 Ryan Bates 最近的 Railscast:http://railscasts.com/episodes/257-request-specs-and-capybara
根据评论更新
respond_with
只会重定向到您在 POST、PUT 或 DELETE 请求中指定的位置。虽然链接中有 :method => :post
,但当禁用 Javascript 时,链接将始终生成 GET 请求(因为您没有使用 AJAX)。如果没有 Javascript,生成 POST 请求的唯一方法是使用表单标记。
如果您希望它在这种情况下正常降级,您应该为这些情况创建一个 html View ,或者在 respond_with
后面放置一个 block ,如下所示:
respond_with(@voted_on_user, :location => user_path(@voted_on_user)) do |format|
format.html { redirect_to user_path(@voted_on_user) }
end`
关于ruby-on-rails - Rspec 测试失败缺少模板格式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5313105/