我是Rails和TDD的新手。目前,我还在用Capybara和RSpec测试我的页面。
我有一个主页上的表单 (root_path),它通过post提交给链接控制器:
<%= form_for @link, url: linkages_path, method: :post, remote: true do |f| %>
<%= f.labels/text_fields... %>
<%= f.submit "Add Link" %>
<% end %>
它到达链接控制器的create操作,理想情况下应该使用AJAX (format.js)更改root_path的数据:
def create
@link = Link.new(params[:link])
if @link.save and current_user.linkages.build(link_id: @link.id).save
flash.now[:success] = "Link to \"#{@link.content}\" was successfully added!"
respond_to do |format|
format.html { redirect root_path }
format.js do
@user_linkage = current_user.linkages
render 'users/user_linkage.js.erb'
end
end
else
flash.now[:error] = "..."
error...
end
end
现在,在成功的情况下,它应该呈现js文件user/user_ file age.js.erb,这就是(它只是在root_path中更改了root_path的div ):
$('#flash').html("<%= escape_javascript(raw(flash_display)) %>");
$('#userLinkage').html("<%= escape_javascript(render partial: 'users/user_linkage_items',
locals: {user_linkage: @user_linkage }) %>");
它在Chrome/Firefox/IE/Opera中运行得很好。然而,当我用Capybara (下面)为它编写测试时,它失败了,因为它重定向回root_path (format.html),而不是呈现format.js块中指定的页面(更改root_path中的数据)。
describe "test" do
let(:link){'some link'}
let(:text){'some text'}
before do
visit root_path
fill_in 'Text', with: link
fill_in 'Link', with: text
end
it "should work" do
expect do
click_button 'Add Link'
end.to change(Link, :count).by(1)
sleep(5)
should have_content(text) # works until here (root_path has same info)
should have_selector('div.alert-success') # fails on this line(flash message)
end
end
所以我知道Capybara只能做GET请求,我的表单已经发布了,但是对于用户模拟来说,内容应该是无关的(?)
如果我将成功时的格式从format.html/format.js更改为以下内容:
respond_to do |format|
format.all do
@user_linkage = current_user.linkages
render 'users/user_linkage.js.erb'
end
end
,然后Capybara最终为我呈现正确的页面,但是如果我在页面上调用save_and_open_page
,那么我会看到所有转义的javascript并错误地呈现have_selector()
,所以我无法测试类似have_selector()
的内容。
我的问题是为什么会这样?是因为Capybara使用GET而不是POST,甚至点击链接也不一定会调用控制器内部的正确格式吗?
P.S.用format.html (排序)切换format.js不起作用-- format.html正在被调用。
发布于 2012-10-08 17:45:02
AFAIK Capybara对POST很好。添加:js => true
,如果你使用的是水豚-webkit。在你的js中你需要.html_safe
$('#userLinkage').html("<%= escape_javascript(render partial: 'users/user_linkage_items',
locals: {user_linkage: @user_linkage }).html_safe %>");
此外,还包括:
current_user.linkages.build(link_id: @link.id).save
可改为:
current_user.linkages.create(link_id: @link.id)
也遵循一些常量缩进方案(两个空格是常用的)。
发布于 2015-11-24 01:19:27
您需要将js: true
添加到测试中。
it "should work", js: true do
https://stackoverflow.com/questions/12785720
复制相似问题