[英]Simple authorization test with RSpec & Capybara failing
我正在尝试使用RSpec和Capybara在我的网站上测试一些授权。 想法是,文章只能由广告管理员或撰写该文章的人编辑。 我没有使用任何宝石,只是一些简单的规则。
这是我的规格:
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
我尝试使用撬来查看@username = @article.user.username
行之前的情况。 似乎我的@article
对象存在,但是从测试中调用.user
返回nil
,因此,在该.username
上调用.username
也会返回nil,从而导致测试失败。
这可以在开发和生产中工作,而不能在测试中工作。 我想知道如何解决这个问题?
谢谢!
尝试对article
的username
进行存根处理,以使其在调用时不nil
:
before(:each) {allow(@article.user).to receive(:username).and_return('username')}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.