我已經在rspec測試中使用設計。這是我的測試設計與rspec測試由於prevoius測試失敗
describe BooksController do
before(:all) do
@user = FactoryGirl.create(:user)
end
describe "GET index" do
it "shows list of current user books" do
sign_in @user
book = @user.books.create!(:title => "user")
get :index, {}
assigns(:books).should eq(@user.books)
end
end
describe "GET show" do
it "assigns the requested book as @book" do
sign_in @user
book = @user.books.create!(:title => "user")
visit_count = book.visits.to_i
get :show, {:id => book.to_param}
assigns(:book).should eq(book)
book = Book.find(book.id)
visit_count.should_not eq(book.visits)
end
end
describe "GET new" do
it "assigns a new book as @book" do
sign_in @user
get :new, {}
assigns(:book).should be_a_new(Book)
end
end
end
工廠
FactoryGirl.define do
factory :user do
sequence(:email) { |n| "foo#{n}@example.com" }
password '12345678'
password_confirmation '12345678'
confirmed_at Time.now
end
end
書控制器
class BooksController < ApplicationController
before_action :authenticate_user!, only: [:index, :edit, :update, :destroy, :new, :my_books, :add_wish_list]
# GET /books
# GET /books.json
def index
@books = current_user.books
end
# GET /books/1
# GET /books/1.json
def show
@book = Book.find(params[:id])
@book.book_visit_count
if(session["warden.user.user.key"].present?)
@book.book_visit_user(session["warden.user.user.key"][0][0])
end
end
# GET /books/new
def new
@book = Book.new
end
end
錯誤
Failure/Error: assigns(:book).should be_a_new(Book)
expected nil to be a new Book(id: integer, title: string, author: string, isbn_10: string, isbn_13: string, edition: integer, print: integer, publication_year: integer, publication_month: string, condition: string, value: integer, status: boolean, stage: integer, description: text, visits: integer, user_id: integer, prefered_place: string, prefered_time: string, created_at: datetime, updated_at: datetime, rating: integer, image: string, publisher: string, goodreads_id: string)
# ./spec/controllers/books_controller_spec.rb:66:in `block (3 levels) in <top (required)>'
當我運行的問題是第三次試驗 「得到新的」 失敗作爲一個整體的測試,但通過時,紅外單獨取消。而且如果我刪除了before_authenticate!然後在控制器中進行所有測試。 同樣,如果我在前兩個描述塊中註釋掉「分配」,則所有測試都會再次通過。 我正在使用rails 4.0.2和rspec 2.14.7,devise 3.2.2
我對rspec很陌生,但不是'之前(:全部)'是否意味着你使用共享對象進行所有測試?也許改成'之前(:每個)'(較慢)或添加一些'之後(:每個)'塊你會清除屬性? – zrl3dx
你只是顯示了你的測試片段? ''before''應該像在以前一樣在'describe'塊之外使用時產生'undefined method'錯誤。 –
是它的一個片段。我會在完整代碼 – surendar