Rails新手.试着按照Michael Hartl的教程.
试图添加辅助方法来模拟RSpec测试中的日志:
describe "when the a user has logged in and attempts to visit the page" do
let(:user) { FactoryGirl.create :user }
before do
log_in user
end
it "should redirect the user to next page" do
specify { response.should redirect_to loggedin_path }
end
end
在我的spec / support / utilities.rb中:
def log_in user
visit root_path
fill_in "Email", with: user.email
fill_in "Password", with: user.password
click_button "Log in"
cookies[:remember_token] = user.remember_token
end
错误:
Failure/Error: log_in user
NoMethodError:
undefined method `cookie_jar' for nil:NilClass
是什么赋予了?
编辑,完整堆栈跟踪:
Index page when the a user has logged in and attempts to visit the page should redirect the user to next page
Failure/Error: log_in user
NoMethodError:
undefined method `cookie_jar' for nil:NilClass
# ./spec/support/utilities.rb:8:in `log_in'
# ./spec/features/pages/index_spec.rb:20:in `block (3 levels) in <top (required)>'
最佳答案 RSpec非常关注您放置测试的目录.如果将测试放在错误的目录中,它将不会自动混合设置不同类型测试的各种测试助手.您的设置似乎正在使用未经批准的
default directory(规格/请求,规格/集成或规格/ API)的规格/功能.
根据教程页面,我不确定他们是如何设置spec_helper.rb文件的.虽然这些例子是他们使用规范/请求来进行测试.
您可以通过使用以下内容强制RSpec识别请求规范的另一个目录:
手动将适当的模块添加到测试文件中:
# spec/features/pages/index_spec.rb
require 'spec_helper'
describe "Visiting the index page" do
include RSpec::Rails::RequestExampleGroup
# Rest of your test code
context "when the a user has logged in and attempts to visit the page" do
let(:user) { FactoryGirl.create :user }
before do
log_in user
end
specify { response.should redirect_to loggedin_path }
end
end
将其包含在spec / spec_helper.rb文件中:
RSpec::configure do |c|
c.include RSpec::Rails::RequestExampleGroup, type: :request, example_group: {
file_path: c.escaped_path(%w[spec (features)])
}
end
由于这是一个教程,我建议遵循以下标准:在spec文件的顶部包含require’spec_helper’,并且您的实际spec / spec_helper.rb文件需要’rspec / rails’
一个小注释,您不需要在它的块内放置一个指定.它们是彼此的别名,所以只需使用一个.
context "when the a user has logged in and attempts to visit the page" do
let(:user) { FactoryGirl.create :user }
before do
log_in user
end
# All of the following are the same
it "redirects the user to next page" do
response.should redirect_to loggedin_path
end
it { response.should redirect_to loggedin_path }
specify "redirects the user to next page" do
response.should redirect_to loggedin_path
end
specify { response.should redirect_to loggedin_path }
end
请注意,根据capybara的文档,您应该能够将您的水豚测试放入规格/功能.要使其工作,请确保在spec_helper或测试规范文件中直接加载require’capybara / rspec’.
但是,看看source,我没有看到它们自动包含该目录的位置.您还可以尝试将标记类型:::添加到测试文件中的外部描述块.虽然更可能的解决方案是使用规范/请求.