2013-04-26 100 views
0

嗨,我正在通過Hartl工作。我已經到了第10章中的微帖子部分,但是我生成了9次失敗,我不明白!Ruby on Rails Hartl教程第10.1.3章我的代碼有問題

Failures: 

    1) Hotel 
    Failure/Error: it {should be_valid} 
     expected valid? to return true, got false 
    # ./spec/models/hotel_spec.rb:19:in `block (2 levels) in <top (required)>' 

    2) Hotel user 
    Failure/Error: its(:user) { should == user } 
     expected: #<User id: 211, name: "Person 80", email: "[email protected]", created_at: "2013-04-26 22:09:22", updated_at: "2013-04-26 22:09:22", password_digest: "$2a$04$ofUpcvsd84qDWTXG131PYedxXdTy2nPzTME/Gf5rc8c0...", remember_token: "wsF59SbMlKni1mqKLhFX0A", admin: false> 
      got: nil (using ==) 
    # ./spec/models/hotel_spec.rb:17:in `block (2 levels) in <top (required)>' 

這是我的hotel_spec.rb文件

require 'spec_helper' 

describe Hotel do 
    let(:user) {FactoryGirl.create(:user)} 
    before {@hotel = user.hotels.build(title: "Hilton", room_description: "Biiiiig Room",include_breakfast: "false", price: 566.6, adress:"Smolnaya")} 

    subject(@hotel) 

    it {should respond_to(:title)} 
    it {should respond_to(:room_description)} 
    it {should respond_to(:include_breakfast)} 
    it {should respond_to(:price)} 
    it {should respond_to(:adress)} 
    it {should respond_to(:user_id)} 
    it {should respond_to(:user)} 

    its(:user) { should == user } 

    it {should be_valid} 

    describe "accesible attributes" do 
     it "should not allow access to user_id" do 
     expect do 
      Hotel.new(user_id: user.id) 
     end.to raise_error(ActiveModel::MassAssignmentSecurity::Error) 
     end 
    end 

    describe "when user_id is not present" do 
     before {@hotel.user_id = nil} 
     it {should_not be_valid} 
    end 

end 

我hotel.rb文件

class Hotel < ActiveRecord::Base 
    attr_accessible :adress, :include_breakfast, :price, :room_description, :title 
    belongs_to :user 

    validates :user_id, presence: true 
end 

,我犯了一個錯誤?任何想法和解決方案大加讚賞。謝謝。

回答

1

@Sunxperous答案似乎是正確的 - 我會建議你使用thoughtbot shoulda gem,使您的測試更簡單。還可以使用FactoryGirl創建您的酒店模型。 rspec可能看起來像寶石

require 'spec_helper' 

describe Hotel do 

    let(:user) { FactoryGirl.create :user } 
    subject(:hotel) { FactoryGirl.create :hotel, user: user } 

    it { should be_valid } # a valid factory is very important 

    it { should_not allow_mass_assignment_of :user_id } 
    it { should validates_presence_of :user } 
    it { should belong_to :user } 

    it {should respond_to(:title)} 
    it {should respond_to(:room_description)} 
    it {should respond_to(:include_breakfast)} 
    it {should respond_to(:price)} 
    it {should respond_to(:adress)} 
    it {should respond_to(:user_id)} 
    it {should respond_to(:user)} 

end 
+0

但是我已經使用FactoryGirl ...並且謝謝你的應該是寶石?很有幫助 – user2325487 2013-04-27 14:49:49

相關問題