为什么控制器规格不合格?

Why controller spec is fail?

我为控制器操作编写规范 create,当我 运行 测试时,shell 显示错误

   expected #count to have changed by 1, but was changed by 0

有规格

let(:valid_attributes) { FactoryGirl.attributes_for(:company) }

describe 'with valid params' do
  it 'creates a new company' do
    expect { post :create, company: valid_attributes }.to change(Company, :count).by(1)

还有工厂

FactoryGirl.define do

  factory :company do
    title Faker::Company.name
    url Faker::Internet.domain_word
    image File.open(File.join(Rails.root, '/spec/fixtures/POEox311zoM.jpg'))
  end
end

怎么解决?我不知道我做错了什么

upd

  def create
    @company = Company.new(company_params)
    if @company.save
      redirect_to root_path
    else
      redirect_to root_path
    end
  end

@object.save@object.save! 之间的区别在于第一个因 returning false 而软失败,这就是为什么我们做 if @object.save 因为如果 return true 如果保存,false 否则。第二个(bang! 方法)抛出一个错误,这更适用于您不检查 return 值的情况,或者可能是 rake 任务。

同样对于你的控制器,你应该处理失败的保存而不是仅仅重定向,例如:

def create
  @company = Company.new(company_params)
  if @company.save
    redirect_to root_path
  else
    render :new
  end
end

这样失败的对象会被传送到 :new 模板,然后你可以处理这些错误,像这样

<% if @company.errors %>
  <% @company.errors.full_messages.each do |message| %>
    <div class='error'><%= message %></div>
  <% end %>
<% end %>

这样模板就会显示错误