我正在开发一个类似Ogame的游戏(https://github.com/arnlen/ogame-like)的培训应用程序。
我正在使用rspec(与Capybara)来测试我的应用程序。我堆叠了几个小时,因为 rspec 抱怨一个错误,*我无法用浏览器自己重现*。
这是我的 rspec 代码:
describe 'Planet pages' do
let(:user){FactoryGirl.create(:user)}
before {sign_in user}
subject {page}
describe "new planet page" do
before {visit new_planet_path}
describe "with valid information" do
before do
visit new_planet_path
fill_in "Name", with: "MyPlanet"
click_button "Validate"
end
# This test doesn't pass
it {should have_selector('h1', text: "Planet")}
end
end
end
失败:
1) Planet pages new planet page with valid information
Failure/Error: it {should have_selector('h1', text: "Planet")}
expected css "h1" with text "Planet" to return something
# ./spec/requests/planet_pages_spec.rb:34:in `block (4 levels) in <top (required)>'
这是涉及的代码。
我的函数"sign_in"被 rspec 使用(位置:spec/support/utilities.rb)
def sign_in(user)
visit signin_path
fill_in "Email", with: user.email
fill_in "Password", with: user.password
click_button "Sign in"
end
我的用户控制器
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:index, :show, :edit, :update, :destroy]
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
sign_in @user
redirect_to new_planet_path
else
render 'new'
end
[...]
我的行星控制器
class PlanetsController < ApplicationController
before_filter :signed_in_user
def index
@planets = current_user.planets
end
def new
@planet = Planet.new
end
def create
@planet = Planet.new(name: params[:planet][:name],
coordinates: generate_coordinates,
metal_ressource: 1000,
user_id: current_user.id)
if @planet.save
flash[:success] = "Welcome on your first planet!"
redirect_to action: 'index'
else
flash[:error] = "Error naming your planet"
render 'new'
end
end
end
和"我的星球索引"视图
<% @planets.each do |planet| %>
<h1>Planet : <%= planet.name %></h1>
<p><%= "Coordinates : #{planet.coordinates}" %></p>
<% end %>
我尝试使用水豚方法"save_and_open_page",但 rspec 引发了错误"未定义的方法"
我还尝试通过对我的规范文件进行迭代来逐步调试,它显示错误发生在"click_button'验证'"之后。由于未知的原因,rspec似乎无法到达planets_path(来自PlanetsController的"索引"操作)。
我出去了,如果有人有想法,我接受!
编辑:已解决 - 发现问题!
使用水豚的"save_and_open_page"方法,我弄清楚了发生了什么:rspec创建的行星没有任何坐标,这是模型不允许的。
如何使用精彩的"save_and_open_page"方法进行调试
- 将此添加到您的宝石文件中:"gem 'launchy'" 安装
- 它:捆绑安装
- 将命令"save_and_open_page"放在您想要的任何位置
希望它能有所帮助。 :)
Capybara 还有一个save_page
方法,它更容易使用,因为它似乎不需要"发射"宝石。页面保存在tmp/capybara
中。在 rspec 测试中,一定要在 before
、it
或其他块中使用save_page
。它不会作为单独的命令工作。例:
before { visit signup_path; save_page }