简体   繁体   English

RSpec和Capybara失败的简单授权测试

[英]Simple authorization test with RSpec & Capybara failing

I'm trying to test some authorization on my website using RSpec & Capybara. 我正在尝试使用RSpec和Capybara在我的网站上测试一些授权。 The idea is that an article can only be editable by ad administrator or the person who wrote the article. 想法是,文章只能由广告管理员或撰写该文章的人编辑。 I'm not using any gems, just a few simple rules. 我没有使用任何宝石,只是一些简单的规则。

This is my spec: 这是我的规格:

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

but running this returns the following error: 但是运行此命令将返回以下错误:

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'

So I look at the articles_controller.rb file and find: 因此,我查看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

I tried using pry to see what happens right before the @username = @article.user.username line. 我尝试使用撬来查看@username = @article.user.username行之前的情况。 It appears as if my @article object exists, but calling .user from my test returns nil and as a consequence, calling .username on that also returns nil, causing the failed test. 似乎我的@article对象存在,但是从测试中调用.user返回nil ,因此,在该.username上调用.username也会返回nil,从而导致测试失败。

This works in development and production, just not in test. 这可以在开发和生产中工作,而不能在测试中工作。 I'm wondering how I can fix this? 我想知道如何解决这个问题?

Thanks! 谢谢!

尝试对articleusername进行存根处理,以使其在调用时不nil

before(:each) {allow(@article.user).to receive(:username).and_return('username')}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM