簡體   English   中英

Ruby on Rails rspec控制器測試失敗,但不應該

[英]Ruby on Rails rspec controller tests are failing, but shouldnt

我有一些控制器測試的問題。 以下兩個都失敗了,但我真的不知道為什么。 更新和銷毀工作正常。

我正在使用Rails 4.0和mongoid。

describe 'POST create' do
context 'with valid attributes' do
  it 'creates a new restaurant' do
    expect {
      post :create, restaurant: FactoryGirl.attributes_for(:random_restaurant)
    }.to change(Restaurant, :count).by(1)
  end

  it 'redirects to the new restaurant' do
    post :create, restaurant: FactoryGirl.attributes_for(:random_restaurant)
    response.should redirect_to Restaurant.last
  end
end

我剛剛添加了從餐館到地址的關系,更新了我的工廠女裝。

這些是我的裝置:

factory :random_restaurant, parent: :restaurant do |r|
  r.name {Faker::Company.name}
  r.description {Faker::Lorem.sentences}

  after(:build) do |restaurant|
    restaurant.addresses << FactoryGirl.build(:random_address)
  end
end

factory :random_address, parent: :address do |a|
  a.street {Faker::Address.street_address}
  a.zip {Faker::Address.zip_code}
  a.city {Faker::Address.city}
end

控制器post create方法看起來像這樣(仍然是默認的)

# POST /restaurants
# POST /restaurants.json
def create
  @restaurant = Restaurant.new(restaurant_params)

  respond_to do |format|
    if @restaurant.save
      format.html { redirect_to @restaurant, notice: 'Restaurant was successfully created.' }
      format.json { render action: 'show', status: :created, location: @restaurant }
    else
      format.html { render action: 'new' }
      format.json { render json: @restaurant.errors, status: :unprocessable_entity }
    end
  end
end

錯誤是:

Failures: 1) RestaurantsController POST create with valid attributes creates a new restaurant
 Failure/Error: expect {
   count should have been changed by 1, but was changed by 0
 # ./spec/controllers/restaurants_controller_spec.rb:39:in `block (4 levels) in <top (required)>'

2) RestaurantsController POST create with valid attributes redirects to the new restaurant
 Failure/Error: response.should redirect_to Restaurant.last
   Expected response to be a <redirect>, but was <200>
 # ./spec/controllers/restaurants_controller_spec.rb:46:in `block (4 levels) in <top (required)>'

Finished in 0.85251 seconds
19 examples, 2 failures

Failed examples:

rspec ./spec/controllers/restaurants_controller_spec.rb:38 # RestaurantsController POST create with valid attributes creates a new restaurant
rspec ./spec/controllers/restaurants_controller_spec.rb:44 # RestaurantsController POST create with valid attributes redirects to the new restaurant

這是一個正在運行的更新測試:

describe 'PUT update' do
before :each do
  @restaurant = FactoryGirl.create(:random_restaurant)
end

context 'with valid attributes' do
  it 'locates the requested @restaurant' do
    put :update, id: @restaurant, restaurant: FactoryGirl.attributes_for(:restaurant)
    assigns(:restaurant).should eq(@restaurant)
  end

  it 'changes @restaurants attributes' do
    put :update, id: @restaurant, restaurant: FactoryGirl.attributes_for(:restaurant)
    @restaurant.reload
    @restaurant.name.should eq('A Lodge')
    @restaurant.description.should eq('A Bar')
  end

  it 'redirects to @restaurant' do
    put :update, id: @restaurant, restaurant: FactoryGirl.attributes_for(:restaurant)
    response.should redirect_to @restaurant
  end
end

有誰知道,為什么這會失敗以及我如何解決它? 非常感謝你

更新 :你的意思是這樣的嗎? 這是來自test.log

Processing by RestaurantsController#create as HTML
Parameters: {"restaurant"=>{"name"=>"Schneider, Franecki and Tillman", 
"description"=>["Quae labore quia officia soluta voluptatibus.", "Et error incidunt beatae laborum a libero officiis.", "Non excepturi dolor vel."], 
"thumbnail"=>"some url", "banner"=>"some url"}}
**Unpermitted parameters: thumbnail, banner**

更新2

這些測試也有效:

describe Restaurant do
  it 'has a valid factory' do
    FactoryGirl.create(:random_restaurant).should be_valid
  end

  it 'has an invalid factory' do
    FactoryGirl.build(:random_restaurant_with_invalid_address).should_not be_valid
  end

  it 'is invalid without a name' do
    FactoryGirl.build(:random_restaurant, name: nil).should_not be_valid
  end

  it 'is invalid without a description' do
    FactoryGirl.build(:random_restaurant, description: nil).should_not be_valid
  end

  it 'is invalid without an address' do
    FactoryGirl.build(:random_restaurant_with_invalid_address).should_not be_valid
  end

  it 'creates an address when created' do
    FactoryGirl.create(:random_restaurant)
  end
end

更新3

我的模特:

class Restaurant
  include Mongoid::Document

  has_many :addresses, dependent: :destroy

  validates :name, presence: true
  validates :description, presence: true
  validates :addresses, presence: true

  field :name, type: String
  field :description, type: String
  field :thumbnail, type: String
  field :banner, type: String
end


class Address
  include Mongoid::Document

  belongs_to :restaurant

  validates :street, presence: true
  validates :zip, presence: true
  validates :city, presence: true

  field :street, type: String
  field :zip, type: Integer
  field :city, type: String

  def full_address
    zip_city = [zip, city].join ' '
    [street, zip_city].join ', '
  end
end

更新4

所以,我發現了這個: 如何在Rails 4中使用attr_accessible?

並更新了我的方法。 但仍然沒有工作:(

def restaurant_params
  params.require(:restaurant).permit(:name, :description, :thumbnail, :banner, addresses_attributes: [ :street, :zip, :city ])
end

只需在控制器上放置一個puts @ restaurant.errors.full_messages,看起來它沒有通過驗證

respond_to do |format|
  if @restaurant.save
    format.html { redirect_to @restaurant, notice: 'Restaurant was successfully created.' }
    format.json { render action: 'show', status: :created, location: @restaurant }
  else
    puts @restaurant.errors.full_messages
    format.html { render action: 'new' }
    format.json { render json: @restaurant.errors, status: :unprocessable_entity }
  end
end

沒有去運行該規范並檢查終端上的輸出

您也可以添加此規范來測試您的工廠,這樣您就可以確保您的工廠正常工作:

it 'creates a valid restaurant from factory girl' do
  rest = FactoryGirl.build :random_restaurant
  rest.should be_valid
end

所以問題在於使用

FactoryGirl.attributes_for(:random_restaurant)

這不是添加地址屬性,您的餐廳驗證至少在屬性的存在。 看一下你問題中的POSTed屬性:

Parameters: {"restaurant"=>{"name"=>"Schneider, Franecki and Tillman", 
               "description"=>["Quae labore quia officia soluta voluptatibus.", 
                               "Et error incidunt beatae laborum a libero officiis.", 
                               "Non excepturi dolor vel."], 
               "thumbnail"=>"some url", "banner"=>"some url"}}

這里沒有地址信息。 當您創建新餐廳時,您至少需要一個地址。 POSTed參數應如下所示:

Parameters: {"restaurant"=>{"name"=>"Schneider, Franecki and Tillman", 
               "description"=>["Quae labore quia officia soluta voluptatibus.", 
                               "Et error incidunt beatae laborum a libero officiis.", 
                               "Non excepturi dolor vel."], 
               "thumbnail"=>"some url", "banner"=>"some url",
               "addresses"=>[{"street" => "...", "city => "...", "zip" => "..."}, ...] }}

我建議您手動為創建案例構建屬性。 如果不出意外,它應該可以幫助您了解控制器如何解析參數

不允許的參數問題是一個單獨的問題,可以在您獲得地址參數后解決。

明白了嗎?

首先,謝謝大家的幫助。 有了你的想法,我得到了一個解決方案,我現在不使用factoryGirl。 我用@PeterGoldstein提到,params。 我弄錯了,我使用的是地址而不是addresses_attributes。 我不知道為什么我必須像我一樣使用它,但我要弄清楚。

現在我的解決方案對我有用:

expect {
      post :create, restaurant: { name: 'A-Lodge', description: 'descr',
                                    thumbnail: 'this is url to thumbnail', banner: 'this is url to banner',
                                    addresses_attributes: [ { street: 'street', zip: '8888', city: 'city' } ] }
    }.to change(Restaurant, :count).by(1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM