我在使用rspec时遇到了一些问题,即使一切都在localhost上运行,也会返回错误。
1) Item pages item creation with invalid information should not create an item
Failure/Error: expect { click_button "Add" }.not_to change(Item, :count)
NoMethodError:
undefined method `node_name' for nil:NilClass
# (eval):2:in `click_button'
# ./spec/requests/item_pages_spec.rb:20:in `block (5 levels) in <top (required)>'
# ./spec/requests/item_pages_spec.rb:20:in `block (4 levels) in <top (required)>'
item_pages_spec.rb
require 'spec_helper'
describe "Item pages" do
subject { page }
let(:user) { FactoryGirl.create(:user) }
let(:list) { FactoryGirl.create(:list, user: user)}
before { sign_in user }
describe "item creation" do
before do
visit user_list_path(user, list)
click_link "Add wish"
end
describe "with invalid information" do
it "should not create an item" do
expect { click_button "Add" }.not_to change(Item, :count)
end
# describe "error messages" do
# before { click_button "Add" }
# it { should have_content('error') }
# end
end
describe "with valid information" do
before { fill_in 'item_title', with: "Lorem ipsum" }
it "should create a item" do
expect { click_button "Add" }.to change(Item, :count).by(1)
end
end
end
end
创建项目的表单
<% if signed_in? %>
<div id="addWish" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="addWishLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="addWishLabel">Add wish</h3>
</div>
<div class="modal-body">
<%= form_for(@item) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.hidden_field :list_id, value: @list.id %>
<%= f.text_field :title, placeholder: "Title..." %>
<%= f.text_field :link, placeholder: "Link..." %>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<%= f.submit "Add", class: "btn btn-primary" %>
<% end %>
</div>
</div>
<% end %>
我对rails非常陌生,因此非常感谢任何帮助!
答案 0 :(得分:0)
expect { click_button "Add" }.to_not change(Item.count)
expect { click_button "Add" }.to_not change(@items, :count)
答案 1 :(得分:0)
如果有其他人来到此处,请检查您的html标签,如@lucas所述。可能是你的情况。我找到了here。 如果您的标签严重关闭,Capybara无法正确找到您的按钮。 就我而言,我有这个:
<div>
<%= form_tag do %>
<%= submit_tag %>
</div>
<% end %>
关闭form_tag之外的div为我做了。