【问题标题】:Why controller spec is fail?为什么控制器规格失败?
【发布时间】:2015-07-07 21:28:57
【问题描述】:

我为控制器操作 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

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

更新

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

【问题讨论】:

  • 没有控制器的代码(它是被测控制器?),它可以是任何东西。
  • 抱歉,我更新一个问题
  • 请发布您的 :company_params 哈希值。
  • 如果保存新公司对你来说都是一样的,你可以跳过 if-else 块。但这可能就是问题所在。找出@company.save 是真还是假。
  • @company.save 替换为@company.save!(用于测试),这样它会抛出一个错误,你就会知道哪里出了问题,可能是验证错误

标签: ruby-on-rails rspec


【解决方案1】:

@object.save@object.save! 之间的区别在于,第一个会通过返回 false 来软失败,这就是我们这样做的原因 if @object.save 因为如果保存则返回 true,否则返回 false。第二个(bang! 方法)会引发错误,这更适合您不检查返回值的情况,或者可能是 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 %>

这样模板会显示错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    相关资源
    最近更新 更多