RSpec 验证在通过 Factory_girl 建立的关联上失败
我确信尝试一些简单的事情而忽略了显而易见的事情。 Factory_Girl 不应该自动创建关联吗?如果是这样,为什么下面的“GET index”规范会失败,因为 event_id
为 nil?
事件 has_many :posts
#post.rb
...
belongs_to :event
validates :event_id, :presence => true
...
#factories.rb
Factory.define :event do |event|
event.name "The Long Event Title"
end
Factory.define :post do |post|
post.title "This is a post"
post.association :event
end
#posts_controller_spec.rb
before(:each) do
@attr = Factory.attributes_for(:post)
end
describe "GET index" do
it "assigns all posts as @posts" do
post = @user.posts.create(@attr) ### <-- event_id not assigned?
# post = FactoryGirl.create(:post) ### <-- this doesn't work either
get :index
assigns(:posts).should eq([post])
end
end
编辑: 其他规范示例:
describe "POST create" do
describe "with valid params" do
it "creates a new Post" do
expect {
post :create, :post => @attr, :event => Factory.create(:event) <- fail
}.to change(Post, :count).by(1)
end
Trying something simple and overlooking the obvious I'm sure. Shouldn't Factory_Girl be automatically creating the association? If so why does "GET index" spec below fail because event_id
is nil?
Event has_many :posts
#post.rb
...
belongs_to :event
validates :event_id, :presence => true
...
#factories.rb
Factory.define :event do |event|
event.name "The Long Event Title"
end
Factory.define :post do |post|
post.title "This is a post"
post.association :event
end
#posts_controller_spec.rb
before(:each) do
@attr = Factory.attributes_for(:post)
end
describe "GET index" do
it "assigns all posts as @posts" do
post = @user.posts.create(@attr) ### <-- event_id not assigned?
# post = FactoryGirl.create(:post) ### <-- this doesn't work either
get :index
assigns(:posts).should eq([post])
end
end
Edit: Additional spec example:
describe "POST create" do
describe "with valid params" do
it "creates a new Post" do
expect {
post :create, :post => @attr, :event => Factory.create(:event) <- fail
}.to change(Post, :count).by(1)
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 FactoryGirl wiki:https://github.com/thoughtbot/factory_girl/wiki/Usage
所以你没有得到 event_id,这就是它失败的原因。
另外,您说您尝试了
post = FactoryGirl.create(:post)
但您应该执行post = Factory.create(:post)
这将使其正常工作。也许在您的 before() 块中,您应该只创建并保存帖子,除非您有一个测试要求尚未保存它。
From the FactoryGirl wiki: https://github.com/thoughtbot/factory_girl/wiki/Usage
So you are not getting an event_id, and that's why it's failing.
Also, you said you tried
post = FactoryGirl.create(:post)
but you should dopost = Factory.create(:post)
and that will get it to work.Perhaps in your before() block you should just create and save the post, unless you have a test that requires it to not be saved yet.
尝试更改
为
Try changing
to