我在模型中添加了一个构造函数
class Movie < Media
attr_accessible :director, :studio
attr_accessor :director, :studio
validates_presence_of :director, :studio, :title
def initialize title, director, studio
@title = title
@director = director
@studio = studio
end
end
那种混乱的东西对我而言。 因为我在我的控制器中有一个方法'new',就像这个
def new
@movies = Movie.new
end
并且在初始化出现之前它运行良好。它需要将参数传递给'new'方法,但这是在视图打开后从用户传递参数并保存它们时完成的。现在我无法打开该视图,因为我收到错误
wrong number of arguments (0 for 3)
由于我开始为我的应用程序编写测试的事实而添加了构造函数,并且为构造函数设置默认值会使该测试无效。关于解决这个问题的建议?
编辑: 我的测试看起来像这样:
require 'spec_helper'
describe Movie do
before :each do
@movie = Movie.new "Bullet", "John", "20th"
end
describe "#{new}" do
it "returns new object of Movie" do
@movie.should be_an_instance_of Movie
end
it "throws ArgumentError when give less than 3 parameters" do
lambda {Movie.new(:director => "John", :studio => "20th")}.should raise_exception ArgumentError
end
end
describe "#title" do
it "returns the correct title" do
@movie.title.should eql "Bullet"
end
end
describe "#director" do
it "returns the correct director" do
@movie.director.should eql "John"
end
end
describe "#studio" do
it "returns the correct studio" do
@movie.studio.should eql "20th"
end
end
end
没有该构造函数,所有测试都会失败....
答案 0 :(得分:9)
ActiveModel提供的默认构造函数非常好。如果删除了你编写的构造函数,你应该能够使用如下的默认构造函数:
@movie = Movie.new(title: 'The Hobbit', director: 'Peter Jackson', studio: 'New Line Cinema')
当您不想提供三个参数时(例如在new
操作中),您可以坚持使用@movie = Movie.new