컨트롤러를 테스트하여 권한있는 사용자 만 RSpec을 사용하여 올바른 하위 객체를 볼 수 있는지 확인하려고합니다. 이 오류가 발생하면 내가 잘못하고있는 것을 파악할 수 없습니다.Model.create를 사용한 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
전화가 나를 위해 이것을 처리 할 것이라고 생각했다. 그러나 명백하게.
여기에 무엇이 누락되어 있으며 무엇이 잘못 되었습니까? 이 시험을 통과하려면 어떻게해야합니까?
당신이뿐만 아니라 컨트롤러 코드를 게시 할 수 있습니까? –
@shioyama - 컨트롤러가 추가되었습니다. –
죄송합니다. 이제 문제가'get : index, {}'전에 발생 했으므로 컨트롤러 코드는별로 중요하지 않습니다. –