我正在尝试测试控制器以确保只有授权方才能使用 RSpec 查看正确的子对象。当我收到此错误时,我无法弄清楚我做错了什么:
ActiveRecord::RecordInvalid: Validation failed: Company can't be blank
我有一个 Plan 对象和一个 Company 对象。商店可以有很多计划(想想害虫防治公司)。我想测试给定一个已知场景,我可以检索公司的计划(假设只有一个)。
该计划如下所示:
class Plan < ActiveRecord::Base
before_save :default_values
# Validation
validates :amount, :presence => true
validates :company, :presence => true
# Plans belong to a particular company.
belongs_to :company, :autosave => true
scope :find_all_plans_for_company, lambda {
|company| where(:company_id => company.id)
}
# Other code ...
end
公司长这样:
class Company < ActiveRecord::Base
validates :name, :presence => true
validates :phone1, :presence => true
validates_format_of :phone1, :phone2,
:with => /^[\(\)0-9\- \+\.]{10,20}$/,
:message => "Invalid phone number, must be 10 digits. e.g. - 415-555-1212",
:allow_blank => true,
:allow_nil => true
has_many :users
has_many :plans
end
.. 控制器看起来像这样
def index
@plans = Plan.find_all_plans_for_company(current_user.company)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @plans }
end
end
.. 我的 RSpec 测试看起来像这样(如果它充满噱头,请原谅,我只是在玩弄它,无法让它工作)。
describe PlansController do
def valid_attributes
{
:company_id => 1,
:amount => 1000
}
end
describe "GET index" do
it "should return the Plans for which this users company has" do
@company = mock_model(Company, :id => 1, :name => "Test Company", :phone1 => "555-121-1212")
Company.stub(:find).with(@company.id).and_return(@company)
controller.stub_chain(:current_user, :company).and_return(@company)
plan = Plan.create! valid_attributes
get :index, {}
assigns(:plans).should eq([plan])
end
# Other tests ...
end
end
问题是,当我尝试这个(或我尝试过的任何疯狂的其他变体)时,我得到了这个错误:
ActiveRecord::RecordInvalid: Validation failed: Company can't be blank
我不确定为什么会发生这种情况,因为我认为Company.stub
电话会为我处理这个问题。但显然不是。
我在这里错过了什么,我做错了什么?我怎样才能让这个测试通过?