簡體   English   中英

RSpec和Capybara失敗的簡單授權測試

[英]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,從而導致測試失敗。

這可以在開發和生產中工作,而不能在測試中工作。 我想知道如何解決這個問題?

謝謝!

嘗試對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