我试图在我的网站上使用RSpec& amp;水豚。我们的想法是,文章只能由广告管理员或撰写文章的人编辑。我没有使用任何宝石,只是一些简单的规则。
这是我的规范:
require 'rails_helper'
require 'capybara/rspec'
describe "the authorization process", :type => :feature do
before :each do
@user = User.new(:id => 3, :email => 'user@example.com', :password => 'password', :password_confirmation => 'password', :username => 'Dummy User')
@user.save
end
it "does not allow a registered user to edit others' articles" do
visit '/login'
within("#new_user") do
fill_in 'Email', :with => 'user@example.com'
fill_in 'Password', :with => 'password'
end
click_button 'Log in'
expect(page).to have_title 'Website Name'
expect(page).to have_content 'Signed in successfully!'
# Seems to be working up to here
visit section_path('mysection')
click_link 'Some link on the page'
expect(current_path).to eq(my_article_path(section: 'mysection', year: 2014, month: 10))
end
end
但运行此命令会返回以下错误:
Failures:
1) the authorization process does not allow a registered user to edit others' articles
Failure/Error: click_link 'Some link on the page'
NoMethodError:
undefined method `username' for nil:NilClass
# ./app/controllers/articles_controller.rb:38:in `show'
所以我查看 articles_controller.rb 文件并找到:
34 def show
35 if @article.nil?
36 redirect_to root_path, alert: "Oops! There are no articles matching a url ending in \"#{params[:id]}\""
37 else
38 @username = @article.user.username
39 end
40 end
我尝试使用pry来查看@username = @article.user.username
行之前发生的事情。看起来好像我的@article
对象存在,但是从我的测试中调用.user
会返回nil
,因此,调用.username
也会返回nil,从而导致测试失败
这适用于开发和生产,而不是测试。我想知道如何解决这个问题?
谢谢!
答案 0 :(得分:1)
尝试隐藏username
的{{1}},以便在调用它时不是article
:
nil